// 语句块

function AddSensorbitCode(Blockly) {

  Blockly.Python.microbitStart = function (block) {
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    let n = 0;
      let code = '';
      let branchCode;
      if (block.getInput('SUBSTACK0')) {
          branchCode = Blockly.Python.statementToCode2(block, 'SUBSTACK0');
          code += `\n${branchCode}\n`;
      }
     
      return `${code}`;
  }
  
  String.prototype.colorRgb = function(){
    var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
    var sColor = this.toLowerCase();
    if(sColor && reg.test(sColor)){
      if(sColor.length === 4){
        var sColorNew = "#";
        for(var i=1; i<4; i+=1){
          sColorNew += sColor.slice(i,i+1).concat(sColor.slice(i,i+1));	
        }
        sColor = sColorNew;
      }
      //处理六位的颜色值
      var sColorChange = [];
      for(var i=1; i<7; i+=2){
        sColorChange.push(parseInt("0x"+sColor.slice(i,i+2)));	
      }
      return  sColorChange.join(",") ;
    }else{
      return sColor;	
    }
  };

  Blockly.Python.microbitLoop = function (block) {
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      const until = block.getFieldValue('MODE') == 'UNTIL';
      let argument0 = Blockly.Python.valueToCode(block, 'BOOL',
        until ? Blockly.Python.ORDER_LOGICAL_NOT :Blockly.Python.ORDER_NONE) || 'True';
        
      let branch = Blockly.Python.statementToCode(block, 'SUBSTACK0');
      branch = Blockly.Python.addLoopTrap(branch, block.id) || Blockly.Python.PASS;
      if (until) {
        argument0 = `!${argument0}`;
      }
    return `while ${argument0}: \ncodeLine1111\n${branch}\n`;
  }
  
  
  Blockly.Python.microbitButton = function (block) {
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    var button = block.getFieldValue('buttonEvent');
    let n = 0;
    var code = '';
    let branchCode;
    var funcName = '';
    var funcStr = "";
    if (block.getInput('SUBSTACK0')) {
      branchCode = Blockly.Python.statementToCode2(block, 'SUBSTACK0');
      code = code + '  ' +  `${branchCode}\n`;
    }
    // code = code.replace(/\s+/g,"  ");
    let codeArr = code.split("\n");
    var code1 =  "";
    for(let i = 0 ; i < codeArr.length; i++) {
        code1 = code1 + "  " + codeArr[i] + "\n";
    }
    code1 = code1.trim();
    var codeResult = code.length == 0?'  pass':'  '+ code1;
    var buttonCode = '';
    if(button === "a"){
        funcStr = 'func_button_a';
        funcName = 'func_button_a=on_button_a()';
        buttonCode = 'def on_button_a():\n'+
        '  while True:\n'+
        '    if button_a.is_pressed() and not button_b.is_pressed():\n'+
        '      yield callback_button_a()\n'+
        '    else:\n'+
        '      yield\n'+
        'def callback_button_a():\n'+
        '  global em_n_my_float_variable, em_s_my_string_variable\n'
        + codeResult;
      }else if(button === "b"){
        funcStr = 'func_button_b';
        funcName = 'func_button_b=on_button_b()';
        buttonCode = 'def on_button_b():\n'+
        '  while True:\n'+
        '    if button_b.is_pressed() and not button_a.is_pressed():\n'+
        '      yield callback_button_b()\n'+
        '    else:\n'+
        '      yield\n'+
        'def callback_button_b():\n'+
        '  global em_n_my_float_variable, em_s_my_string_variable\n'
        + codeResult;
      }else{
        funcStr = 'func_button_ab';
        funcName = 'func_button_ab=on_button_ab()';
        buttonCode = 'def on_button_ab():\n'+
        '  while True:\n'+
        '    if button_a.is_pressed() and  button_b.is_pressed():\n'+
        '      yield callback_button_ab()\n'+
        '    else:\n'+
        '      yield\n'+
        'def callback_button_ab():\n'+
        '  global em_n_my_float_variable, em_s_my_string_variable\n'
        + codeResult;
      }
    Blockly.Python.definitions_['import_microbitDef'+button] = buttonCode;
    return funcName+'\n';
  }
  
  
   Blockly.Python.statementToCode2 = function(block, name) {
    var targetBlock = block.getInputTargetBlock(name);
    var code = Blockly.Python.blockToCode(targetBlock);
    return code;
  };
  
    
  
  
    // Blockly.Python.control_start = function (block) {
    //   Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    //   return '';
    // };
  
    //显示数字
    Blockly.Python.displayShowNumber = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var number = Blockly.Python.valueToCode(this, 'displayShowNumber', Blockly.Python.ORDER_ATOMIC);
      return 'display.scroll(' + number + ')\n';
    };
  
    //显示图片
    Blockly.Python.displayShowImageView = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var image = block.getFieldValue('image');
      return 'display.show(' + image + ')\n';
    };
  
    //显示字符串
    Blockly.Python.displayShowString = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var string = Blockly.Python.valueToCode(this, 'displayShowString', Blockly.Python.ORDER_ATOMIC);
      return 'display.scroll(str(' + string.replace(/'/g, '') + '))\n';
    };
  
    //暂停   睡眠
    Blockly.Python.pauseSleep = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      // var time = block.getFieldValue('time');
      var sleepTime = Blockly.Python.valueToCode(this, 'sleepTime', Blockly.Python.ORDER_ATOMIC);
      return 'sleep(' + sleepTime + ')\n';
    };
  
    //清除屏幕
    Blockly.Python.emptyScreen = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      return 'display.clear()\n';
    };
  
    //显示方向
    Blockly.Python.displayShowArrow = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var displayShowArrow = block.getFieldValue('displayShowArrow');
      return 'display.show(' + displayShowArrow + ')\n';
    };
  
    //当按钮被按下
    Blockly.Python.buttonPressed = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var Button = block.getFieldValue('Button');
      var cod = '';
      if (Button === 'A') {
        cod = 'if button_a.is_pressed():'
      } else if (Button === 'B') {
        cod = 'if button_b.is_pressed():'
      } else if (Button === 'A+B') {
        cod = 'if button_a.is_pressed() and button_b.is_pressed():'
      }
      var code = 'while True:';
      var branch = Blockly.Python.statementToCode(this, 'DO');
      branch = Blockly.Python.addLoopTrap(branch, block.id) ||
        Blockly.Python.PASS;
      var code2 = `${cod} \n${branch}\n`;
      // Blockly.Python.definitions_['func_timer'] = code2;
      return code2;
    };
  
    // var branch = Blockly.Python.statementToCode(block, 'SUBSTACK');
    //   branch = Blockly.Python.addLoopTrap(branch, block.id) ||
    //     Blockly.Python.PASS;
    //   var loopVar = Blockly.Python.variableDB_.getDistinctName(
    //     'count', Blockly.Variables.NAME_TYPE);
    //   var code = 'for ' + loopVar + ' in range(' + repeats + '):\n' + branch;
    //   return code;
  
    //当微标朝上
    Blockly.Python.stateChange = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var Button = block.getFieldValue('state');
      console.log(Button)
      var cod = '';
      if (Button == 'shock') {
        cod = 'if accelerometer.was_gesture("shake"):'
      } else if (Button == 'up') {
        cod = 'if accelerometer.was_gesture("up"):'
      } else if (Button == 'down') {
        cod = 'if accelerometer.was_gesture("down"):'
      } else if (Button == 'left') {
        cod = 'if accelerometer.was_gesture("left"):'
      } else if (Button == 'right') {
        cod = 'if accelerometer.was_gesture("right"):'
      } else if (Button == 'screenup') {
        cod = 'if accelerometer.was_gesture("face up"):'
      } else if (Button == 'screendown') {
        cod = 'if accelerometer.was_gesture("face down"):'
      } else if (Button == 'fall') {
        cod = 'if accelerometer.was_gesture("freefall"):'
      } else if (Button == '3g') {
        cod = 'if accelerometer.was_gesture("3g"):'
      } else if (Button == '6g') {
        cod = 'if accelerometer.was_gesture("6g"):'
      } else if (Button == '8g') {
        cod = 'if accelerometer.was_gesture("8g"):'
      }
      var code = 'while True:';
      var branch = Blockly.Python.statementToCode(this, 'DO');
      branch = Blockly.Python.addLoopTrap(branch, block.id) ||
        Blockly.Python.PASS;
      var code2 = `${cod} \n${branch}\n`;
      // Blockly.Python.definitions_['func_timer'] = code2;
      return code2;
    };
  
    //当引脚被按下
    Blockly.Python.pinTouched = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var pin = block.getFieldValue('Pin');
      var cod = '';
      if (pin === 'p0') {
        cod = 'if pin0.is_touched():'
      } else if (pin === 'p1') {
        cod = 'if pin1.is_touched():'
      } else if (pin === 'p2') {
        cod = 'if pin2.is_touched():'
      }
      var code = 'while True:';
      var branch = Blockly.Python.statementToCode(this, 'DO');
      branch = Blockly.Python.addLoopTrap(branch, block.id) ||
        Blockly.Python.PASS;
      var code2 = `${cod} \n${branch}\n`;
      // Blockly.Python.definitions_['func_timer'] = code2;
      return code2;
    };
  
    //按钮是否被按下  
    Blockly.Python.buttonPressedTowState = function (block) {
      var Button = block.getFieldValue('Button');
      var cod = '';
      if (Button === 'A') {
        cod = 'button_a.is_pressed()'
      } else if (Button === 'B') {
        cod = 'button_b.is_pressed()'
      } else if (Button === 'A+B') {
        cod = 'button_a.is_pressed() and button_b.is_pressed()'
      }
      return [cod, Blockly.Python.ORDER_ATOMIC];
    };
  
    
  
    //引脚是否被接通
    Blockly.Python.pinPressedTowState = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var pin = block.getFieldValue('PinState');
      var cod = '';
      if (pin === 'p0') {
        cod = 'pin0.is_touched()'
      } else if (pin === 'p1') {
        cod = 'pin1.is_touched()'
      } else if (pin === 'p2') {
        cod = 'pin2.is_touched()'
      }
      return [cod, Blockly.Python.ORDER_ATOMIC]
    };
  
    //加速度
    Blockly.Python.accelerationValue = function (block) {
      var acceleration = block.getFieldValue('acceleration');
      var cod = '123'
      if (acceleration == 'x') {
        cod = 'accelerometer.get_x()'
      } else if (acceleration == 'y') {
        cod = 'accelerometer.get_y()'
      } else if (acceleration == 'z') {
        cod = 'accelerometer.get_z()'
      }
      return [cod, Blockly.Python.ORDER_ATOMIC];
    };
  
  
    //亮度级别
    Blockly.Python.brightnessLevel = function (block) {
      return ['display.get_pixel(2, 2)', Blockly.Python.ORDER_ATOMIC];
    };
  
    //指南针朝向
    Blockly.Python.pointerOrientation = function (block) {
      return ['compass.heading()', Blockly.Python.ORDER_ATOMIC]
    };
  
    //温度
    Blockly.Python.temperaTure = function (block) {
      return ['temperature()', Blockly.Python.ORDER_ATOMIC]
    };
  
    //旋转方式
    Blockly.Python.rotationMode = function (block) {
      var pin = block.getFieldValue('rotation');
      var cod = '';
      if (pin == 'rotate') {
        cod = 'accelerometer.get_y()'
      } else if (pin == 'roll') {
        cod = 'accelerometer.get_x()'
      }
      return [cod, Blockly.Python.ORDER_ATOMIC]
    };
  
  
    //磁力
    Blockly.Python.magneticForce = function (block) {
      var acceleration = block.getFieldValue('magnetic');
      var cod = '123'
      if (acceleration == 'x') {
        cod = 'compass.get_x()'
      } else if (acceleration == 'y') {
        cod = 'compass.get_y()'
      } else if (acceleration == 'z') {
        cod = 'compass.get_z()'
      }
      return [cod, Blockly.Python.ORDER_ATOMIC]
    };
  
    //运行时间
    Blockly.Python.runningTime = function (block) {
      //return 'display.scroll(' + string.replace(/'/g, '"') + ')\n';
      return ['running_time()', Blockly.Python.ORDER_ATOMIC]
    };
  
    //校准指南针
    Blockly.Python.calibrateCompass = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      return 'compass.calibrate()\n';
    };
  
    //当引脚被释放时  
    Blockly.Python.pinPressedThreeState = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var pin = block.getFieldValue('State');
      var cod = '';
      if (pin === 'p0') {
        cod = 'while pin0.is_touched():\n' + "    " + 'sign = 1\n' + "  " + 'if sign == 1:\n' + "    " + 'sign = 0 '
      } else if (pin === 'p1') {
        cod = 'while pin1.is_touched():\n' + "    " + 'sign = 1\n' + "  " + 'if sign == 1:\n' + "    " + 'sign = 0 '
      } else if (pin === 'p2') {
        cod = 'while pin2.is_touched():\n' + "    " + 'sign = 1\n' + "  " + 'if sign == 1:\n' + "    " + 'sign = 0 '
      }
      var code = 'while True:';
      var branch = Blockly.Python.statementToCode(this, 'DO');
      branch = Blockly.Python.addLoopTrap(branch, block.id) ||
        Blockly.Python.PASS;
      var code2 = `${cod} \n${branch}\n`;
      // Blockly.Python.definitions_['func_timer'] = code2;
      return code2;
    };
  
    //Music
    //播放音调 playTone
    Blockly.Python.playTone = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitmusic'] = 'import music';
      var tone = block.getFieldValue('tone');
      var rhythm = block.getFieldValue('rhythm');
      var playPin = block.getFieldValue('playPin');
      rhythm = parseInt(rhythm * 500);
      return 'music.pitch(' + tone + ', ' + rhythm + ', '+ playPin +')\n';
    };
  
    //播放铃声
    Blockly.Python.playRingTone = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitmusic'] = 'import music';
      var tone = block.getFieldValue('tone');
      var playPin = block.getFieldValue('playPin');
      return 'music.pitch(' + tone +', '+ playPin + ', -1)\n';
    };
  
    //暂停播放（ms）
    Blockly.Python.pausePlayback = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitmusic'] = 'import music';
      var rhythm = block.getFieldValue('rhythm');
      rhythm = rhythm * 500;
      rhythm = parseInt(rhythm);
      return 'music.pitch(0, ' + rhythm + ')\n';
    };
  
    //播放旋律
    Blockly.Python.playMelody = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitmusic'] = 'import music';
      var song = block.getFieldValue('song');
      var playPin = block.getFieldValue('playPin');
      var frequency = block.getFieldValue('frequency');
      var code = "";
      if (frequency == "once") {
        code = 'for i in range(1):\n music.play(' + song + ', '+ playPin +')\n';
      } else if (frequency == "loop") {
        code = 'while True:\n music.play(' + song + ', '+ playPin + ')\n';
      }
      return code;
    };
  
    //palyTime
    Blockly.Python.palyTime = function (block) {
      return 'null\n';
    };
  
    //stopMelody
    Blockly.Python.stopMelody = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitmusic'] = ' import music';
      var stopPin = block.getFieldValue('stopPin');
      return 'music.stop('+ stopPin +')\n';
    };
  
    //tone
    Blockly.Python.tone = function (block) {
      var tone = block.getFieldValue('tone');
      return tone;
    };
  
    //rhythm
    Blockly.Python.rhythm = function (block) {
      var rhythm = block.getFieldValue('rhythm');
      return rhythm;
    };
  
    //bpm
    Blockly.Python.bpm = function (block) {
      return 'bpm';
    };
  
    //将节奏更改为（bpm）
    Blockly.Python.bpmChange = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitmusic'] = 'import music';
      var bpm = Blockly.Python.valueToCode(this, 'bpm', Blockly.Python.ORDER_ATOMIC);
      if (bpm <= 0) {
        bpm = 20;
      }
      return 'music.set_tempo(bpm='+ bpm + ')\n';
    };
  
    //将节奏设定为（bpm）
    Blockly.Python.bpmSetting = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitmusic'] = 'import music';
      var bpm = Blockly.Python.valueToCode(this, 'bpm', Blockly.Python.ORDER_ATOMIC);
      if (bpm <= 0) {
        bpm = 120;
      }
      bpm = parseInt(bpm);
      return 'music.set_tempo(bpm=' + bpm + ')\n';
    };
  
    //LED
    //绘图
    lightlevel = 9;
    Blockly.Python.drawing = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var x = Blockly.Python.valueToCode(this, 'x', Blockly.Python.ORDER_ATOMIC);
      var y = Blockly.Python.valueToCode(this, 'y', Blockly.Python.ORDER_ATOMIC);
      return 'display.set_pixel(' + x + ', ' + y + ', '+ lightlevel +')\n';
  
    };
  
    //取消绘图
    Blockly.Python.cancelMapping = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var x = Blockly.Python.valueToCode(this, 'x', Blockly.Python.ORDER_ATOMIC);
      var y = Blockly.Python.valueToCode(this, 'y', Blockly.Python.ORDER_ATOMIC);
      return 'display.set_pixel(' + x + ', ' + y + ', 0)\n';
    };
  
    //切换绘图
    Blockly.Python.switchMapping = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var x = Blockly.Python.valueToCode(this, 'x', Blockly.Python.ORDER_ATOMIC);
      var y = Blockly.Python.valueToCode(this, 'y', Blockly.Python.ORDER_ATOMIC);
      return 'if display.get_pixel(' + x + ', ' + y + '):\n display.set_pixel(' + x + ', ' + y + ', 0)\nelse:\n display.set_pixel(' + x + ', ' + y + ', '+ lightlevel +') \n';
    };
  
    //点图
    Blockly.Python.spotMapping = function (block) {
      var x = Blockly.Python.valueToCode(this, 'x', Blockly.Python.ORDER_ATOMIC);
      var y = Blockly.Python.valueToCode(this, 'y', Blockly.Python.ORDER_ATOMIC);
      var code = 'display.get_pixel(' + x + ', ' + y + ')';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //绘制条形图
    Blockly.Python.drawBarType = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var x = Blockly.Python.valueToCode(this, 'x', Blockly.Python.ORDER_ATOMIC);
      var y = Blockly.Python.valueToCode(this, 'y', Blockly.Python.ORDER_ATOMIC);
      //return 'display.get_pixel(' + x + ',' + y + ')\n';
      return 'line = [2, 1, 3, 0, 4]\nrow = [4, 3, 2, 1, 0]\ndef bar_chart(variable, highest):\n  sign, line_GPS, row_GPS= 1, 0, 0\n  for i in range(0, min([variable, highest])*10000, (highest*10000)//15):\n    ' +
        'if row_GPS == 5:\n      break\n    if sign:\n      sign = 0\n      display.set_pixel(2, row[row_GPS], '+ lightlevel +')\n      line_GPS += 1\n    else:\n      for j in range(2):\n        ' +
        'display.set_pixel(line[line_GPS], row[row_GPS], '+ lightlevel +')\n        line_GPS += 1\n    if line_GPS == 5:\n      line_GPS = 0\n      row_GPS += 1\n      sign = 1\n  for i in range(row_GPS, 5):\n    ' +
        'for j in range(line_GPS, 5):\n      display.set_pixel(line[j], row[i], 0)\n    line_GPS = 0\n  sleep(50)\nbar_chart(' + x + ', ' + y + ')\n';
    };
  
    //绘图 加入亮度条件
    Blockly.Python.drawingLight = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var x = Blockly.Python.valueToCode(this, 'x', Blockly.Python.ORDER_ATOMIC);
      var y = Blockly.Python.valueToCode(this, 'y', Blockly.Python.ORDER_ATOMIC);
      var brightness =Blockly.Python.valueToCode(this, 'brightness', Blockly.Python.ORDER_ATOMIC);
      return 'display.set_pixel(' + x + ', ' + y + ', ' + brightness + ')\n';
    };
  
    //亮度
    Blockly.Python.brightness = function (block) {
      if (lightlevel != null) {
        return [lightlevel, Blockly.Python.ORDER_ATOMIC]
      }
      return ["ERROR", Blockly.Python.ORDER_ATOMIC];
    };
  
    //设置亮度
    Blockly.Python.setBrightness = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      lightlevel = Blockly.Python.valueToCode(this, 'brightness', Blockly.Python.ORDER_ATOMIC);
      if(lightlevel>9){
        lightlevel = 9;
      }else if(lightlevel < 0){
        lightlevel = 0;
      }
      return 'lightlevel = ' + lightlevel + '\n';
    };
  
    //停止动画
    Blockly.Python.stopAnimation = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      return 'display.clear()\n';
    };
  
    //LED启用
    Blockly.Python.LEDEnabled = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var boolean_ = block.getFieldValue('boolean_');
      if (boolean_ == "true") {
        lightlevel = 8;
      } else {
        lightlevel = 0;
      }
      return '';
    };
  
    //wifi
    //无线设置组
    Blockly.Python.wifiSetting = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitRadio'] = 'import radio';
      var setWifi = Blockly.Python.valueToCode(this, 'setWifi', Blockly.Python.ORDER_ATOMIC);
      return 'radio.config(channel=' + setWifi + ')\n';
    };
  
    //打开无线设置组
    Blockly.Python.openWifi = function (block) {
     Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
     Blockly.Python.definitions_['import_microbitRadio'] = 'import radio';
     var wifiSwitch =block.getFieldValue('wifiSwitch'); 
     return 'radio.' + wifiSwitch + '\n';
   };
    //无线发送数字
    Blockly.Python.wifiSendNumber = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitRadio'] = 'import radio';
      // Blockly.Python.definitions_['import_microbitOnRadio'] = 'radio.on()';
      var setWifiNumber = Blockly.Python.valueToCode(this, 'setWifiNumber', Blockly.Python.ORDER_ATOMIC);
      // setWifiNumber = setwifiString.replace(/"/g, '');
      return 'radio.send("' + setWifiNumber + '")\n';
    };
  
    //无线发送字符串
    Blockly.Python.wifiSettingString = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitRadio'] = 'import radio';
      // Blockly.Python.definitions_['import_microbitOnRadio'] = 'radio.on()';
      var setwifiString = Blockly.Python.valueToCode(this, 'setwifiString', Blockly.Python.ORDER_ATOMIC);
      setwifiString = setwifiString.replace(/'/g,"");
      // setwifiString =  setwifiString.replace(/"/g, '') ;
      return 'radio.send(' + setwifiString + ')\n';
    };
  
  
    //无线发送值
    Blockly.Python.wifiSettingValue = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitRadio'] = 'import radio';
      // Blockly.Python.definitions_['import_microbitOnRadio'] = 'radio.on()';
      var setWifiName = Blockly.Python.valueToCode(this, 'setWifiName', Blockly.Python.ORDER_ATOMIC);
      var setWifiValue = Blockly.Python.valueToCode(this, 'setWifiValue', Blockly.Python.ORDER_ATOMIC);
      return 'radio.send(' + setWifiName.replace(/"/g, '') + '+' + setWifiValue + ')\n';
    };
  
    Blockly.Python.receivingData = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitRadio'] = 'import radio';
      // Blockly.Python.definitions_['import_microbitOnRadio'] = 'radio.on()';
      var code = 'radio.receive()';
      return [code, Blockly.Python.ORDER_ATOMIC];
    };
    
    //在无线接收到数据时运行 receivedNumber
    Blockly.Python.receivingDataStatusOne = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitRadio'] = 'import radio';
      // Blockly.Python.definitions_['import_microbitOnRadio'] = 'radio.on()';
      var cod = 'receivedNumber=radio.receive()\nif receivedNumber = ‘6’:';
      var branch = Blockly.Python.statementToCode(this, 'DO');
      var code2 = `${cod} \n ${branch}\n`;
      return code2;
    };
  
    //在无线接收到数据时运行 receivedNumber
    Blockly.Python.receivingDataStatusTwo = function (block) {
      Blockly.Python.definitions_['import_microbitOnRadio'] = 'radio.on()';
      var cod = 'incoming=radio.receive()\nif incoming = “microbit123”:';
      var branch = Blockly.Python.statementToCode(this, 'DO');
      var code2 = `${cod} \n ${branch}\n`;
      return code2;
    };
  
    //在无线接收到数据时运行 receivedNumber
    Blockly.Python.receivingDataStatusThree = function (block) {
      Blockly.Python.definitions_['import_microbitOnRadio'] = 'radio.on()';
      var cod = 'if receivedString = “microbit”: ';
      var branch = Blockly.Python.statementToCode(this, 'DO');
      var code2 = `${cod} \n ${branch}\n`;
      return code2;
    };
  
    //接收到的数据包
    Blockly.Python.packetsReceived = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitRadio'] = 'import radio';
      Blockly.Python.definitions_['import_microbitRadio'] = 'import time';
      // Blockly.Python.definitions_['import_microbitOnRadio'] = 'radio.on()';
      var acceleration = block.getFieldValue('magnetic');
      var code = 'if radio.receive():\n whentime = time.ticks_ms()';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //无线设置发射功率 power
    Blockly.Python.wifiTansmitPower = function (block) {
      var power = block.getFieldValue('power');
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitRadio'] = 'import radio';
      Blockly.Python.definitions_['import_microbitOnRadio'] = 'radio.on()';
      // var power = Blockly.Python.valueToCode(this, 'power', Blockly.Python.ORDER_ATOMIC);
      return 'radio.config(power= ' + power + ')\n';
    };
  
    //数学
    //initData
    Blockly.Python.initData = function (block) {
      var data = Blockly.Python.valueToCode(this, 'data', Blockly.Python.ORDER_ATOMIC);
      return [parseInt(data)];
    };
  
    //余数
    Blockly.Python.remainder = function (block) {
      var data1 = Blockly.Python.valueToCode(this, 'data1', Blockly.Python.ORDER_ATOMIC);
      var data2 = Blockly.Python.valueToCode(this, 'data2', Blockly.Python.ORDER_ATOMIC);
      var result = ''+data1+' % '+data2+'';
      return [result, Blockly.Python.ORDER_ATOMIC];
    };
  
    //两个数间的最大值于最小值
    Blockly.Python.betweenNumbers = function (block) {
      var most = block.getFieldValue('most');
      var data1 = Blockly.Python.valueToCode(this, 'data1', Blockly.Python.ORDER_ATOMIC);
      var data2 = Blockly.Python.valueToCode(this, 'data2', Blockly.Python.ORDER_ATOMIC);
      data1 = parseInt(data1);
      data2 = parseInt(data2);
      var result = "";
      if (most == "min") {
        // if (data1 > data2) {
        //   result = data2 + 1;
        // } else {
        //   result = data1 + 1;
        // }
        result = 'min('+data1+', '+data2+')'
      } else if (most == "max") {
        // if (data1 > data2) {
        //   result = data1 - 1;
        // } else {
        //   result = data2 - 1;
        // }
        result = 'max('+data1+', '+data2+')'
      }
      // if (data2 == data1) {
      //   result = data1;
      // }
      return [result, Blockly.Python.ORDER_ATOMIC];
    };
  
    //绝对值
    Blockly.Python.absoluteValue = function (block) {
      var data = Blockly.Python.valueToCode(this, 'absolute', Blockly.Python.ORDER_ATOMIC);
      data = parseInt(data.replace(/'/g, ''));
      var result = Math.abs(data);
      result = 'abs('+data+')';
      return [result, Blockly.Python.ORDER_ATOMIC];
    };
  
    //平方根
    Blockly.Python.squareRoot = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_math'] = 'import math';
      var data = Blockly.Python.valueToCode(this, 'data', Blockly.Python.ORDER_ATOMIC);
      var type = block.getFieldValue('type');
      var result = '';
      if(type == 'sqrt'){
        result = 'math.sqrt('+data+') ';
      }else if(type == 'sin'){
        result = 'math.sin('+data+') ';
      }else if(type == 'cos'){
        result = 'math.cos('+data+') ';
      }else if(type == 'tan'){
        result = 'math.tan('+data+') ';
      }else if(type == 'atan2'){
        result = 'math.atan2('+data+') ';
      }
      return [result, Blockly.Python.ORDER_ATOMIC];
    };
  
    //选取随机数
  Blockly.Python.selectRandomNumber = function (block) {
    Blockly.Python.definitions_['import_random'] = 'import random';
    var data1 = Blockly.Python.valueToCode(this, 'data1', Blockly.Python.ORDER_ATOMIC);
    var data2 = Blockly.Python.valueToCode(this, 'data2', Blockly.Python.ORDER_ATOMIC);
    data1 = parseInt(data1);
    data2 = parseInt(data2);
    var max = "";
    var min = "";
    if (data1 > data2) {
      max = data1;
      min = data2;
    } else {
      max = data2
      min = data1;
    }
    var Range = max - min;
    var Rand = Math.random();
    var result = "random.randint("+ min + ", " + max +")";   
    return [result, Blockly.Python.ORDER_ATOMIC];
  };
  
    //随机选取true或者false
    Blockly.Python.randomBoolean = function (block) {
      var randomNumber = Math.floor(Math.random() * (100 - 0)) + 0;
      var result = ""
      if (randomNumber % 2 == 1) {
        result = 'True';
      } else {
        result = 'False';
      }
      return [result, Blockly.Python.ORDER_ATOMIC];
    };
    
     //
     Blockly.Python.transferInt = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var data = Blockly.Python.valueToCode(this, 'data', Blockly.Python.ORDER_ATOMIC);
      var result = 'int(' + data + ')';
      return [result, Blockly.Python.ORDER_ATOMIC];
    };

    //数组
    //返回数组长度
    Blockly.Python.listLength = function (block) {
      var code = 'len()';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //从数组 L 中取得索引 5 的值
    Blockly.Python.getListIndexValue = function (block) {
      var index = Blockly.Python.valueToCode(this, 'index', Blockly.Python.ORDER_ATOMIC);
      var code = 'L(' + index + ')';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //将数组 L 中索引为0 的值设置为 4
    Blockly.Python.setListIndexValue = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var index = Blockly.Python.valueToCode(this, 'index', Blockly.Python.ORDER_ATOMIC);
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
      return 'L.pop(' + index + ')\nL.insert(' + index + ', ' + value + ')\n';
    };
  
    //添加值到list中
    Blockly.Python.addValueToList = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
      return 'L.append(' + value + ')\n';
    };
  
    //获取并移除数组中最后一个值
    Blockly.Python.removeEndValue = function (block) {
      var code = 'L.pop()';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //查找某个值在数组中的下标
    Blockly.Python.getValuePosition = function (block) {
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
      var code = 'L.index(' + value + ')';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //获取并移除 L 中的第一个值
    Blockly.Python.removeStartValue = function (block) {
      var code = 'L.pop(0)';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //L 在开头插入 5
    Blockly.Python.addValueToListHead = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
      return 'L.insert(0, ' + value + ')\n';
    };
  
    //L 在 0 处插入值  5
    Blockly.Python.addValueToListPosition = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var index = Blockly.Python.valueToCode(this, 'index', Blockly.Python.ORDER_ATOMIC);
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
      return 'L.insert(' + index + ', ' + value + ')\n';
    };
  
    //L移除 2 处的值
    Blockly.Python.removePositionValue = function (block) {
      var index = Blockly.Python.valueToCode(this, 'index', Blockly.Python.ORDER_ATOMIC);
      var code = 'L.pop(' + index + ')';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //L移除 2 处的值
    Blockly.Python.nullValue = function (block) {
      var code = 'L = []\n';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //文本
  
    //空值s
    Blockly.Python.nullValue = function (block) {
      var inputText = Blockly.Python.valueToCode(this, 'inputText', Blockly.Python.ORDER_ATOMIC);
      inputText = inputText.replace(/'/g,"");
      return [inputText, Blockly.Python.ORDER_ATOMIC]
    };
  
    //返回字符的长度
    Blockly.Python.returnStringLength = function (block) {
      var inputText = Blockly.Python.valueToCode(this, 'inputText', Blockly.Python.ORDER_ATOMIC);
      var code = 'len(' + inputText + ')';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //比较两个字符串 string_compare(' + inputText1 + ',' + inputText2 + ')
    Blockly.Python.comparativeText = function (block) {
      var inputText1 = Blockly.Python.valueToCode(this, 'inputText1', Blockly.Python.ORDER_ATOMIC);
      var inputText2 = Blockly.Python.valueToCode(this, 'inputText2', Blockly.Python.ORDER_ATOMIC);
      var code = 'def string_compare(str_one, str_two):\n'+
      '    if str_one > str_two:\n'+
      '        return 1\n'+
      '    elif str_one < str_two:\n'+
      '        return -1\n'+
      '    else:\n'+
      '        return 0\n';
      Blockly.Python.definitions_['import_textFuncDef'] = code;
      var result = 'string_compare(' + inputText1 + ', ' + inputText2 + ')';
      return [result, Blockly.Python.ORDER_ATOMIC];
      // 
    };
  
    //获取字符串中的一部分 
    Blockly.Python.getSubString = function (block) {
      var startPosition = Blockly.Python.valueToCode(this, 'startPosition', Blockly.Python.ORDER_ATOMIC);
      var length = Blockly.Python.valueToCode(this, 'length', Blockly.Python.ORDER_ATOMIC);
      var inputText = Blockly.Python.valueToCode(this, 'inputText', Blockly.Python.ORDER_ATOMIC);
      inputText = inputText.replace(/'/g,"");
      var code = inputText+'[' + startPosition + ':' + length + ']';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //判断字符串是否为空
    Blockly.Python.isEmptyText = function (block) {
      var inputText = Blockly.Python.valueToCode(this, 'inputText', Blockly.Python.ORDER_ATOMIC);
      //return inputText.replace(/ /g, "") == ""?true:false;
      inputText = inputText.replace(/'/g,"");
      var code = 'not ' + inputText + '.strip()';
      return [code, Blockly.Python.ORDER_ATOMIC]
    }
  
    //将字符串转化为number类型
    Blockly.Python.parseToNumber = function (block) {
      var inputText = Blockly.Python.valueToCode(this, 'inputText', Blockly.Python.ORDER_ATOMIC);
      inputText = inputText.replace(/'/g,"");
      var code = 'int(' + inputText + ')';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //获取字符串中的一部分
    Blockly.Python.getIndexChar = function (block) {
      var inputText = Blockly.Python.valueToCode(this, 'inputText', Blockly.Python.ORDER_ATOMIC);
      var startPosition = Blockly.Python.valueToCode(this, 'startPosition', Blockly.Python.ORDER_ATOMIC);
      var endPosition = parseInt(startPosition) + 1;
      inputText = inputText.replace(/'/g,"");
      var code = '' + inputText + '[' + startPosition + ':' + endPosition + ']';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //提取字符代码中的文本
    Blockly.Python.extractText = function (block) {
      var inputText = Blockly.Python.valueToCode(this, 'inputText', Blockly.Python.ORDER_ATOMIC);
      var code = 'chr(' + inputText + ')';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //convert to text
    Blockly.Python.convertToText = function (block) {
      var integer = Blockly.Python.valueToCode(this, 'integer', Blockly.Python.ORDER_ATOMIC);
      var code = "str("+integer + ")";
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //游戏
    //创建精灵
    Blockly.Python.creatingElves = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var x = Blockly.Python.valueToCode(this, 'x', Blockly.Python.ORDER_ATOMIC);
      var y = Blockly.Python.valueToCode(this, 'y', Blockly.Python.ORDER_ATOMIC);
      sprite = { x: x, y: y, angle: 0, light: 0, LED_time: 100, score: 0, pause: 0 };
      var code = 'display.set_pixel(' + sprite.x + ', ' + sprite.y + ', 9)';
      return [code, Blockly.Python.ORDER_ATOMIC];
    };
  
    //删除精灵
    Blockly.Python.deleteElves = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var lablex = sprite.x;
      var labley = sprite.y;
      sprite = null;
      var code = 'display.set_pixel(' + lablex + ', ' + labley + ', 0)\n';
      return [code, Blockly.Python.ORDER_ATOMIC];
    };
  
    //精灵移动
    Blockly.Python.moveSprite = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var move = Blockly.Python.valueToCode(this, 'move', Blockly.Python.ORDER_ATOMIC);
      return 'def LED_move(move_vagle):\nglobal location[0], location[1], angle\nmove_two = {45:[ location[0] + move_vagle, location[1] + move_vagle], 135:[ location[0] - move_vagle, location[1] + move_vagle], 225:[ location[0] - move_vagle, location[1] - move_vagle], 315:[ location[1] - move_vagle, location[0] + move_vagle]}}\n'
        + 'if angle == 90:\n  location[1] += move_vagle\nelif angle == 180:\n  location[0] -= move_vagle\nelif angle == 270:\n  location[1] -= move_vagle\nelif angle == 360 or angle == 0:\n  location[0] += move_vagle\nelse:\n  location[0] = move_two[angle][0]\n  location[1] = move_two[angle][1]\n  location[0] = 4 if location[0] > 4 else 0 if location[0] < 0 else location[0]\n  location[1] = 4 if location[1] > 4 else 0 if location[1] < 0 else location[1]\n  display.set_pixel(location[0], location[1], 9)\n'+
        'LED_move('+ move +')\n';
    };
  
    //精灵转向
    Blockly.Python.turnSprite = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var turn = block.getFieldValue('turn');
      var direction = "";
      if (turn == "左转") {
        direction = 1;
      } else {
        direction = 0;
      }
      var angle_move_value = Blockly.Python.valueToCode(this, 'turn', Blockly.Python.ORDER_ATOMIC);
      return 'def angle_move(direction,angle_move_value):\n  global angle\n  if direction:\n  for i in range(0, angle_move_value, 45):\n'
        + '    if angle == 0:\n      angle = 360\n    angle -= 45\n  else:\n  for i in range(0, angle_move_value, 45):\n    if angle == 360:\n      angle = 0\n    angle += 45\nangle_move('+ direction +','+ angle_move_value +')';
    };
  
    //精灵更改幅度
    Blockly.Python.updateSpriteAxis = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var axis = block.getFieldValue('axis');
      var code = "";
      if (axis == "x") {
        code = 'display.set_pixel('+sprite.x+', '+sprite.y+', 0)\n'+sprite.x+' = 4 if '+sprite.x+'+1 > 4 else 0 if '+sprite.x+'+1 < 0 else '+sprite.x+'+1\ndisplay.set_pixel('+sprite.x+', '+sprite.y+', 9)';
      } else {
        code = 'display.set_pixel('+sprite.x+' '+sprite.y+', 0)\n'+sprite.y+' = 4 if '+sprite.y+'+1 > 4 else 0 if '+sprite.y+'+1 < 0 else '+sprite.y+'+1\ndisplay.set_pixel('+sprite.x+', '+sprite.y+', 9)';
      }
      return code + '\n';
    };
  
    //精灵Sprite设置轴
    Blockly.Python.setSpriteAxis = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var axis = block.getFieldValue('axis');
      var setValue = Blockly.Python.valueToCode(this, 'set', Blockly.Python.ORDER_ATOMIC);
      if (axis == "x") {
        sprite.x= setValue;
      } else {
        sprite.y = setValue;
      }
      return 'display.set_pixel(' + sprite.x + ',' + sprite.y + ',9)\n';
    };
  
    //精灵获取sprite轴
    Blockly.Python.getSpriteAxis = function (block) {
      var axis = block.getFieldValue('axis');
      if (axis == "x") {
        return sprite.x+"";
      } else {
        return sprite.y+"";
      }
    };
  
    //精灵是否遇到
    // Blockly.Python.isMeest = function (block) {
    //   var axis = block.getFieldValue('axis');
    //   var set = Blockly.Python.valueToCode(this, 'set', Blockly.Python.ORDER_ATOMIC);
    //   if (axis == "x") {
    //     return sprite[0];
    //   } else {
    //     return sprite[1];
    //   }
    // };
  
    //精灵是否碰到边缘
    Blockly.Python.isTouchEdge = function (block) {
      if (sprite.x == 0 || sprite.x == 4 || sprite.y == 0 || sprite.y == 4) {
        return 'True';
      } else {
        return 'False';
      }
    };
  
    //如果sprite碰到边缘则反弹
    Blockly.Python.touchEdgeEvent = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      return 'if('+sprite.x+' == 0 || '+sprite.x+' == 4 || '+sprite.y+' == 0 || '+sprite.y+' == 4)\n  if angle >= 180:\n    angle -= 180\n  else:\n    angle += 180\n';
    };
  
    //将分数更改
    Blockly.Python.isTouchEdge = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var fraction = Blockly.Python.valueToCode(this, 'fraction', Blockly.Python.ORDER_ATOMIC);
      sprite.score += fraction;
      return 'sprite.score += '+ fraction +'\n';
    };
  
    //设置分数
    Blockly.Python.setFractions = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var fraction = Blockly.Python.valueToCode(this, 'fraction', Blockly.Python.ORDER_ATOMIC);
      sprite.score = fraction;
      return 'sprite.score = '+ fraction +'\n';
    };
  
    //setLife
    Blockly.Python.setLife = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var lifeNumber = Blockly.Python.valueToCode(this, 'life', Blockly.Python.ORDER_ATOMIC);
      sprite.life = lifeNumber;
      return 'sprite.life = '+ lifeNumber +'\n';
    };
  
    //addLife
    Blockly.Python.addLife = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var lifeNumber = Blockly.Python.valueToCode(this, 'life', Blockly.Python.ORDER_ATOMIC);
      sprite.life += lifeNumber;
      return 'sprite.life += '+ lifeNumber +'\n';
    };
  
    //removeLife
    Blockly.Python.removeLife = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var lifeNumber = Blockly.Python.valueToCode(this, 'life', Blockly.Python.ORDER_ATOMIC);
      sprite.life -= lifeNumber;
      return 'sprite.life -= '+ lifeNumber +'\n';
    };
  
    //getFraction
    Blockly.Python.getFraction = function (block) {
      return sprite.score+"";
    };
  
    //gameOver
    Blockly.Python.gameOver = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      return '  for i in range(8):\n    display.show(Image("99999:99999:99999:99999:99999"))\n    sleep(300)\n    display.show(Image("00000:00000:00000:00000:00000"))\n' +
        '    sleep(300)\n  lift = 0\n  display.scroll("GAME OVER SCORE")\n  display.scroll(str(score))\n';
    };
  
    //isGameOver
    Blockly.Python.isGameOver = function (block) {
      if(sprite.life <= 0){
        return "True\n";
      }else {
        return "False\n";
      }
    };
  
    //isPaused
    Blockly.Python.isPaused = function (block) {
      if(sprite.pause == 1){
        return "True\n";
      }else {
        return "False\n";
      }
    };
  
    //isRunning
    Blockly.Python.isRunning = function (block) {
      if(sprite.score > 0 && sprite.pause == 0){
        return "True\n";
      }else {
        return "False\n";
      }
    };
  
    //paused
    Blockly.Python.paused = function (block) {
      sprite.paused = 1;
      return 'paused\n';
    };
  
    
    //recovery
    Blockly.Python.recovery = function (block) {
      sprite.paused = 0;
      return 'recovery\n';
    };
  
    //图像
    //创建图像
    Blockly.Python.createImage = function (block) {
      var choice = block.getFieldValue('CHOICE');
      if (choice.length <= 0) {
        choice = "0000000000000000000000000";
      }
      var choiceArrray = [];
      for (var i = 0; i < choice.length / 5; i++) {
        choiceArrray.push(choice.substring(i * 5, i * 5 + 5).replace(/1/g, '8'))
      }
      var microbitImage = 'Image("' + choiceArrray[0] + ':' + choiceArrray[1] + ':' + choiceArrray[2] + ':' + choiceArrray[3] + ':' + choiceArrray[4] + '")';
      return [microbitImage, Blockly.Python.ORDER_ATOMIC]
    };
  
    //显示图像
    Blockly.Python.showImage = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var microbitImage = Blockly.Python.valueToCode(this, 'myImage', Blockly.Python.ORDER_ATOMIC);
      var position = Blockly.Python.valueToCode(this, 'position', Blockly.Python.ORDER_ATOMIC);
      var orientation = block.getFieldValue('orientation');
      console.log(microbitImage);
      var code = "";
      if (orientation == "UP") {
        code = 'display.show(' + microbitImage + '.shift_up(' + position + '))';
      } else if (orientation == "DOWN") {
        code = 'display.show(' + microbitImage + '.shift_down(' + position + '))';
      } else if (orientation == "LEFT") {
        code = 'display.show(' + microbitImage + '.shift_left(' + position + '))';
      } else if (orientation == "RIGHT") {
        code = 'display.show(' + microbitImage + '.shift_right(' + position + '))';
      }
      return code + '\n';
      //return 'display.show('+microbitImage+'.shift_left('+ position +')))';
    };
  
    //滚动图像
    Blockly.Python.rollImage = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var position = Blockly.Python.valueToCode(this, 'position', Blockly.Python.ORDER_ATOMIC);
      var time = Blockly.Python.valueToCode(this, 'time', Blockly.Python.ORDER_ATOMIC);
      var orientation = block.getFieldValue('orientation');
      var microbitImage = Blockly.Python.valueToCode(this, 'myImage', Blockly.Python.ORDER_ATOMIC);
      var code = "";
      if (orientation == "上") {
        code = 'for i in range(0, 5, ' + position + '):\n  display.show(' + microbitImage + '.shift_down(5-i))\n  sleep(' + time + ')\n' +
          'for i in range(0, 5, ' + position + '):\n  display.show(' + microbitImage + '.shift_up(i))\n  sleep(' + time + ')';
      } else if (orientation == "下") {
        code = 'for i in range(0, 5, ' + position + '):\n  display.show(' + microbitImage + '.shift_down(i))\n  sleep(' + time + ')';
      } if (orientation == "左") {
        code = 'for i in range(0, 5, ' + position + '):\n  display.show(' + microbitImage + '.shift_left(i))\n  sleep(' + time + ')\n' +
          'for i in range(0, 5, ' + position + '):\n  display.show(' + microbitImage + '.shift_right(4-i))\n  sleep(' + time + ')';
      } else if (orientation == "右") {
        code = 'for i in range(0, 5, ' + position + '):\n  display.show(' + microbitImage + '.shift_right(5-i))\n  sleep(' + time + ')';
      }
      return code;
      //return 'for i in range(0, 5, 2):\n  display.show(Image("80000:08000:00800:00080:00008").shift_up(5-i))\n  sleep(500)';
    };
  
    //创建图像
    Blockly.Python.arrowImage = function (block) {
      var arrow = block.getFieldValue('arrow');
      var microbitImage;
      if (arrow == 'north') {//北
        microbitImage = 'Image("00100:01110:10101:00100:00100")';
      } else if (arrow == 'south') {//南
        microbitImage = 'Image("00100:00100:10101:01110:00100")';
      } else if (arrow == 'west') {//东
        microbitImage = 'Image("00100:01000:11111:01000:00100")';
      } else if (arrow == 'east') {//西
        microbitImage = 'Image("00100:00010:11111:00010:00100")';
      } else if (arrow == 'southwest') {//西南
        microbitImage = 'Image("00001:00010:10100:11000:11100")';
      } else if (arrow == 'northwest') {//东南
        microbitImage = 'Image("11100:11000:10100:00010:00001")';
      } else if (arrow == 'southeast') {//西北
        microbitImage = 'Image("10000:01000:00101:00011:00111")';
      } else if (arrow == 'northeast') {//东北
        microbitImage = 'Image("00111:00011:00101:01000:10000")';
      }
      microbitImage = microbitImage.replace(/1/g, '8');
      return [microbitImage, Blockly.Python.ORDER_ATOMIC]
    };
    //引脚
    //数字读取引脚
    Blockly.Python.digitalReadPin = function (block) {
      var pin = block.getFieldValue('pin');
      var code = '' + pin + '.read_digital()';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //向引脚数字写入值
    Blockly.Python.writeDigitalValue = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var pin = block.getFieldValue('pin');
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
      return '' + pin + '.write_digital(' + value + ')\n';
    };
  
    //模拟读取引脚
    Blockly.Python.analogReadPin = function (block) {
      var pin = block.getFieldValue('pin');
      var code = '' + pin + '.read_analog()';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //向引脚数字写入模拟值
    Blockly.Python.writeAnalogValue = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var pin = block.getFieldValue('pin');
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
      return '' + pin + '.write_analog(' + value + ')\n';
    };
  
    //设置引脚模拟期间
    Blockly.Python.setSimulationPeriod = function (block) {
      return null;
    };
  
    //映射
    Blockly.Python.mapping = function (block) {
      var a = Blockly.Python.valueToCode(this, 'mapping', Blockly.Python.ORDER_ATOMIC);
      var b = Blockly.Python.valueToCode(this, 'low', Blockly.Python.ORDER_ATOMIC);
      var c = Blockly.Python.valueToCode(this, 'high', Blockly.Python.ORDER_ATOMIC);
      var d = Blockly.Python.valueToCode(this, 'tolow', Blockly.Python.ORDER_ATOMIC);
      var e = Blockly.Python.valueToCode(this, 'tohigh', Blockly.Python.ORDER_ATOMIC);
      var code = '' + a + ' * ((' + e + ' - ' + d + ') / (' + c + ' - ' + b + '))';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //向伺服机构引脚P0写入angle
    Blockly.Python.writeServoValue = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var pin = block.getFieldValue('pin');
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
      return pin + '.write_analog((0.5 + ' + value + '/90)*1023/15)\n';
    };
  
    //将伺服机构 引脚P0 脉冲设置
    Blockly.Python.setServoPulse = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var pin = block.getFieldValue('pin');
      var value = Blockly.Python.valueToCode(this, 'pulse', Blockly.Python.ORDER_ATOMIC);
      return  pin + '.set_analog_period(' + value + ')\n';
    };
  
    //当引脚状态改变时
    Blockly.Python.statusChangesEvent = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var pin = block.getFieldValue('pin');
      var status = block.getFieldValue('status');
      var cod = '';
      if (status == 'high') {
        cod = 'if ' + pin + '.read_digital:'
      } else if (status == 'low') {
        cod = 'if not ' + pin + '.read_digital:'
      }
      var branch = Blockly.Python.statementToCode(this, 'DO')  || Blockly.Python.PASS;
      var code2 = `${cod} \n ${branch}\n`;
      return code2;
    };
  
  
    //脉冲引脚持续时间（μs）——
    Blockly.Python.pulseDurationPin = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_utime'] = 'import utime';
      var pin = block.getFieldValue('pin');
      var status = block.getFieldValue('status');
      var code ='';
      var highCode = 'def durationHighTime(pin):\n'+
        '    time = 0\n'+
        '    if pin.read_digital():\n'+
        '        time_start = utime.ticks_ms()\n'+
        '        while pin.read_digital():\n'+
        '            pass\n'+
        '        time = utime.ticks_ms() - time_start\n'+
        '    return time\n';
      var lowCode = 'def durationLowTime(pin):\n'+
      '    time = 0\n'+
      '    if not pin.read_digital():\n'+
      '        time_start = utime.ticks_ms()\n'+
      '        while not pin.read_digital():\n'+
      '            pass\n'+
      '        time = utime.ticks_ms() - time_start\n'+
      '    return time\n';
      Blockly.Python.definitions_['import_defHighTime'] = highCode;
      Blockly.Python.definitions_['import_defLowTime'] = lowCode;
      if (status == "high") {
        code = 'durationHighTime('+ pin + ')';
      } else if (status == "low") {
        code = 'durationLowTime('+ pin + ')';
      }
      return  [code, Blockly.Python.ORDER_ATOMIC];
    };
  
    //i2cReadNumber
    Blockly.Python.i2cReadNumber = function (block) {
      return 'null';
    };
  
    //i2cWriteNumber
    Blockly.Python.i2cWriteNumber = function (block) {
      return 'null';
    };
  
    //spi写入 4
    Blockly.Python.spiWrite = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
      var code = 'spi.write(bytes(' + value + '))';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //模拟音阶
    Blockly.Python.analogueScale = function (block) {
      return 'null';
    };
  
    //设置引脚 P0 以激发 边缘 事件   
    Blockly.Python.setPinEvents = function (block) {
      return 'null';
    };
  
    //spi频率 1000000
    Blockly.Python.spiFrequency = function (block) {
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
      return 'spi.init(baudrate=' + value + ')\n';
    };
  
    //设置模拟音阶引脚
    Blockly.Python.setAnalogScalePin = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitmusic'] = 'import music';
      var pin = block.getFieldValue('pin');
      var frequency = Blockly.Python.valueToCode(this, 'frequency', Blockly.Python.ORDER_ATOMIC);
      var time = Blockly.Python.valueToCode(this, 'time', Blockly.Python.ORDER_ATOMIC);
      return 'music.pitch(' + frequency + ', ' + time + ', pin=' + pin + ', wait=True)\n';
    };
  
    //设置拉 引脚music。
    Blockly.Python.setPullPin = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      return 'null';
    };
  
    //spi 格式 位数
    Blockly.Python.spiFormatDigits = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var value = block.getFieldValue('value');
      var mode = block.getFieldValue('mode');
      // var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
      // var mode = Blockly.Python.valueToCode(this, 'mode', Blockly.Python.ORDER_ATOMIC);
      return 'spi.init(bits=' + value + ', mode=' + mode + ')  \n';
    };
  
    //spi 设置引脚
    Blockly.Python.spiSetPin = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var mosi = block.getFieldValue('mosi');
      var miso = block.getFieldValue('miso');
      var sdk = block.getFieldValue('sdk');
      return 'spi.init(sclk=' + sdk + ', mosi=' + mosi + ', miso=' + miso + ')\n';
    };
  
    //串行
    //串口打印microbit
    Blockly.Python.serialPrintingString = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
      value = value.replace(/'/g,"");
      return 'print(' + value + ')\n';
    };
  
    //向串口写入一行
    Blockly.Python.writeLineToSerial = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
      value = value.replace(/'/g,"");
      return 'uart.write(bytearray(' + value + '+"\\n"))\n';
    };
  
    //串口写入数字
    Blockly.Python.writeNumberToSerial = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
      var value = "\"" + value + "\"";
      return 'uart.write(bytearray(' + value + '+"\\n"))\n';
    };
  
    //串口写入数值
    Blockly.Python.writeValueToSerial = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var name = Blockly.Python.valueToCode(this, 'name', Blockly.Python.ORDER_ATOMIC);
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
      return 'uart.write((bytearray(' + value + '+' + name + '+"\\n"))\n';
    };
  
    //串口写入字符串
    Blockly.Python.writeStringToSerial = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
      return 'uart.write((bytearray(' + value + ')))\n';
    };
  
    // //串口写入字符串
    // Blockly.Python.writeStringToSerial = function (block) {
    //   var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
    //   return 'uart.write((bytearray(' + value + '))\n';
    // };
  
    //从串口读取行
    Blockly.Python.readLineToSerial = function (block) {
      var code = 'uart.readline()';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //从串口读取，直至遇到 换行
    Blockly.Python.readSerialData = function (block) {
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
      var code = 'index = 0\nvalue = ' + value + '\nwhile True:\nif uart.any():\none_byte = uart.read(1)\n'
        + 'if ord(one_byte)!=36:\nvalue[index] = one_byte\nindex += 1\nelse:\nbreak';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //串口读取字符串
    Blockly.Python.readSerialString = function (block) {
      var code = 'uart.read()';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //串口写入字符串
    Blockly.Python.serialStatusChangesEvent = function (block) {
      return 'null';
    };
  
    //串行 重定向
    Blockly.Python.serialRedirection = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var pinTX = block.getFieldValue('pinTX');
      var pinRX = block.getFieldValue('pinRX');
      var baudRate = block.getFieldValue('baudRate');
      return 'uart.init(baudrate=' + baudRate + ', bits=8, parity=None, stop=1, tx=' + pinTX + ', rx=' + pinRX + ') \n';
    };
  
    //串行 重定向到USB
    Blockly.Python.serialRedirectionUSB = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      return 'uart.init(115200)\n';
    };
  
  
    //控制
    //重置
    Blockly.Python.reset = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      return 'reset()\n';
    };
  
    //等待（μs）
    Blockly.Python.waiting = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbit_utime'] = 'import utime';
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
      return 'utime.sleep_us(' + value + ')\n';
    };
  
  
    Blockly.Python['controls_if'] = function (block) {
      var n = 0;
      var code = '', branchCode, conditionCode;
      do {
        conditionCode = Blockly.Python.valueToCode(block, 'CONDITION' + n,
          Blockly.Python.ORDER_NONE) || 'False';
        branchCode = Blockly.Python.statementToCode(block, 'SUBSTACK' + n) ||
          Blockly.Python.PASS;
        code += (n > 0 ? 'else ' : '') +
          'if ' + conditionCode + ':\n' + branchCode + '';
        ++n;
      } while (block.getInput('IF' + n));
  
      if (block.getInput('SUBSTACK2')) {
        branchCode = Blockly.Python.statementToCode(block, 'SUBSTACK2') ||
          Blockly.Python.PASS;
        code += 'else:\n' + branchCode + '';
      }
      return code + '\n';
    };
  
    Blockly.Python.control_if_else = Blockly.Python.controls_if;
  
    // 控制：while循环
    Blockly.Python._while = function (block) {
      var value__whiles = Blockly.Python.valueToCode(this, '_whiles', Blockly.Python.ORDER_ATOMIC);
      if (value__whiles.includes('true')) value__whiles = 'True';
      const branch = Blockly.Python.statementToCode(this, 'DO') || Blockly.Python.PASS;;
      const code2 = `while ${value__whiles.replace(/'/g, '')}: \n${branch}\n`;
      return code2;
    };
  
    // 显示屏显赫字符串
    Blockly.Python['displayShow'] = function (block) {
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
      return 'display.scroll(' + value + ')\n';
    }
  
    Blockly.Python['displayShowClear'] = function (block) {
      // var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
      return 'display.clear()\n';
    }
  
  
    // dowhile
    Blockly.Python.dowhile = function () {
      let value_dowhiles = Blockly.Python.valueToCode(this, 'dowhiles', Blockly.Python.ORDER_ATOMIC);
      if (value_dowhiles === true) value_dowhiles = True;
      let branch = Blockly.Python.statementToCode(this, 'DO');
      let code = `do :\n${branch}while ${value_dowhiles.replace(/'/g, '')}\n`;
      return code;
    };
  
    Blockly.Python['control_wait'] = function (block) {
      var repeats = Blockly.Python.valueToCode(block, 'DURATION',
        Blockly.Python.ORDER_ASSIGNMENT) || '0';
      return 'sleep(' + repeats + ')\n';
    };
  
    Blockly.Python['data_variable'] = function (block) {
      // Variable getter.
      var code = Blockly.Python.variableDB_.getName(block.getFieldValue('VARIABLE'),
        Blockly.Variables.NAME_TYPE);
      return [code, Blockly.Python.ORDER_ATOMIC];
    };
  
    Blockly.Python['data_setvariableto'] = function (block) {
      // Variable setter.
      var argument0 = Blockly.Python.valueToCode(block, 'VALUE',
        Blockly.JavaScript.ORDER_ASSIGNMENT) || '0';
      var varName = Blockly.Python.variableDB_.getName(
        block.getFieldValue('VARIABLE'), Blockly.Variables.NAME_TYPE);
      return varName + ' = ' + argument0 + ';\n';
    };
  
    Blockly.Python['text'] = function (block) {
      // Text value.
      var code = Blockly.Python.quote_(block.getFieldValue('TEXT'));
      return [code, Blockly.Python.ORDER_ATOMIC];
    };
  
    /**
     * Enclose the provided value in 'String(...)' function.
     * Leave string literals alone.
     * @param {string} value Code evaluating to a value.
     * @return {string} Code evaluating to a string.
     * @private
     */
    Blockly.Python.text.forceString_ = function (value) {
      if (Blockly.Python.text.forceString_.strRegExp.test(value)) {
        return value;
      }
      return 'String(' + value + ')';
    };
  
    /**
     * Regular expression to detect a single-quoted string literal.
     */
    Blockly.Python.text.forceString_.strRegExp = /^\s*'([^']|\\')*'\s*$/;
  
    Blockly.Python['text_join'] = function (block) {
      // Create a string made up of any number of elements of any type.
      switch (block.itemCount_) {
        case 0:
          return ['\'\'', Blockly.Python.ORDER_ATOMIC];
        case 1:
          var element = Blockly.Python.valueToCode(block, 'ADD0',
            Blockly.Python.ORDER_NONE) || '\'\'';
          var code = Blockly.Python.text.forceString_(element);
          return [code, Blockly.Python.ORDER_FUNCTION_CALL];
        case 2:
          var element0 = Blockly.Python.valueToCode(block, 'ADD0',
            Blockly.Python.ORDER_NONE) || '\'\'';
          var element1 = Blockly.Python.valueToCode(block, 'ADD1',
            Blockly.Python.ORDER_NONE) || '\'\'';
          var code = Blockly.Python.text.forceString_(element0) + ' + ' +
            Blockly.Python.text.forceString_(element1);
          return [code, Blockly.Python.ORDER_ADDITION];
        default:
          var elements = new Array(block.itemCount_);
          for (var i = 0; i < block.itemCount_; i++) {
            elements[i] = Blockly.Python.valueToCode(block, 'ADD' + i,
              Blockly.Python.ORDER_COMMA) || '\'\'';
          }
          var code = '[' + elements.join(',') + '].join(\'\')';
          return [code, Blockly.Python.ORDER_FUNCTION_CALL];
      }
    };
  
    Blockly.Python.control_repeat = function (block) {
  
  
      // Repeat n times.
      if (block.getField('TIMES')) {
        // Internal number.
        var repeats = String(parseInt(block.getFieldValue('TIMES'), 10));
      } else {
        // External number.
        var repeats = Blockly.Python.valueToCode(block, 'TIMES',
          Blockly.Python.ORDER_NONE) || '0';
      }
      if (Blockly.isNumber(repeats)) {
        repeats = parseInt(repeats, 10);
      } else {
        repeats = 'int(' + repeats + ')';
      }
      var branch = Blockly.Python.statementToCode(block, 'SUBSTACK');
      branch = Blockly.Python.addLoopTrap(branch, block.id) ||
        Blockly.Python.PASS;
      var loopVar = Blockly.Python.variableDB_.getDistinctName(
        'count', Blockly.Variables.NAME_TYPE);
      var code = 'for ' + loopVar + ' in range(' + repeats + '):\n' + branch;
      return code;
    };
  
    Blockly.Python['controls_repeat'] = Blockly.Python['control_repeat'];
  
    Blockly.Python.control_forever = function (block) {
      // Do while/until loop.
      const until = block.getFieldValue('MODE') == 'UNTIL';
      let argument0 = Blockly.Python.valueToCode(block, 'BOOL',
        until ? Blockly.Python.ORDER_LOGICAL_NOT :
          Blockly.Python.ORDER_NONE) || 'True';
      let branch = Blockly.Python.statementToCode(block, 'SUBSTACK');
      branch = Blockly.Python.addLoopTrap(branch, block.id) ||
        Blockly.Python.PASS;
      if (until) {
        argument0 = `!${argument0}`;
      }
      return `while ${argument0}: \n${branch}\n`;
    };
  
    Blockly.Python['text_append'] = function (block) {
      // Append to a variable in place.
      var varName = Blockly.Python.variableDB_.getName(
        block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
      var value = Blockly.Python.valueToCode(block, 'TEXT',
        Blockly.Python.ORDER_NONE) || '\'\'';
      return varName + ' += ' + Blockly.Python.text.forceString_(value) + ';\n';
    };
  
    Blockly.Python['text_length'] = function (block) {
      // String or array length.
      var text = Blockly.Python.valueToCode(block, 'VALUE',
        Blockly.Python.ORDER_FUNCTION_CALL) || '\'\'';
      return [text + '.length', Blockly.Python.ORDER_MEMBER];
    };
  
    Blockly.Python['text_isEmpty'] = function (block) {
      // Is the string null or array empty?
      var text = Blockly.Python.valueToCode(block, 'VALUE',
        Blockly.Python.ORDER_MEMBER) || '\'\'';
      return ['!' + text + '.length', Blockly.Python.ORDER_LOGICAL_NOT];
    };
  
    Blockly.Python['text_indexOf'] = function (block) {
      // Search the text for a substring.
      var operator = block.getFieldValue('END') == 'FIRST' ?
        'indexOf' : 'lastIndexOf';
      var substring = Blockly.Python.valueToCode(block, 'FIND',
        Blockly.Python.ORDER_NONE) || '\'\'';
      var text = Blockly.Python.valueToCode(block, 'VALUE',
        Blockly.Python.ORDER_MEMBER) || '\'\'';
      var code = text + '.' + operator + '(' + substring + ')';
      // Adjust index if using one-based indices.
      if (block.workspace.options.oneBasedIndex) {
        return [code + ' + 1', Blockly.Python.ORDER_ADDITION];
      }
      return [code, Blockly.Python.ORDER_FUNCTION_CALL];
    };
  
    Blockly.Python['text_charAt'] = function (block) {
      // Get letter at index.
      // Note: Until January 2013 this block did not have the WHERE input.
      var where = block.getFieldValue('WHERE') || 'FROM_START';
      var textOrder = (where == 'RANDOM') ? Blockly.Python.ORDER_NONE :
        Blockly.Python.ORDER_MEMBER;
      var text = Blockly.Python.valueToCode(block, 'VALUE',
        textOrder) || '\'\'';
      switch (where) {
        case 'FIRST':
          var code = text + '.charAt(0)';
          return [code, Blockly.Python.ORDER_FUNCTION_CALL];
        case 'LAST':
          var code = text + '.slice(-1)';
          return [code, Blockly.Python.ORDER_FUNCTION_CALL];
        case 'FROM_START':
          var at = Blockly.Python.getAdjusted(block, 'AT');
          // Adjust index if using one-based indices.
          var code = text + '.charAt(' + at + ')';
          return [code, Blockly.Python.ORDER_FUNCTION_CALL];
        case 'FROM_END':
          var at = Blockly.Python.getAdjusted(block, 'AT', 1, true);
          var code = text + '.slice(' + at + ').charAt(0)';
          return [code, Blockly.Python.ORDER_FUNCTION_CALL];
        case 'RANDOM':
          var functionName = Blockly.Python.provideFunction_(
            'textRandomLetter',
            ['function ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ +
              '(text) {',
              '  var x = Math.floor(Math.random() * text.length);',
              '  return text[x];',
              '}']);
          var code = functionName + '(' + text + ')';
          return [code, Blockly.Python.ORDER_FUNCTION_CALL];
      }
      throw Error('Unhandled option (text_charAt).');
    };
  
    /**
     * Returns an expression calculating the index into a string.
     * @param {string} stringName Name of the string, used to calculate length.
     * @param {string} where The method of indexing, selected by dropdown in Blockly
     * @param {string=} opt_at The optional offset when indexing from start/end.
     * @return {string} Index expression.
     * @private
     */
    Blockly.Python.text.getIndex_ = function (stringName, where, opt_at) {
      if (where == 'FIRST') {
        return '0';
      } else if (where == 'FROM_END') {
        return stringName + '.length - 1 - ' + opt_at;
      } else if (where == 'LAST') {
        return stringName + '.length - 1';
      } else {
        return opt_at;
      }
    };
  
    Blockly.Python['text_getSubstring'] = function (block) {
      // Get substring.
      var text = Blockly.Python.valueToCode(block, 'STRING',
        Blockly.Python.ORDER_FUNCTION_CALL) || '\'\'';
      var where1 = block.getFieldValue('WHERE1');
      var where2 = block.getFieldValue('WHERE2');
      if (where1 == 'FIRST' && where2 == 'LAST') {
        var code = text;
      } else if (text.match(/^'?\w+'?$/) ||
        (where1 != 'FROM_END' && where1 != 'LAST' &&
          where2 != 'FROM_END' && where2 != 'LAST')) {
        // If the text is a variable or literal or doesn't require a call for
        // length, don't generate a helper function.
        switch (where1) {
          case 'FROM_START':
            var at1 = Blockly.Python.getAdjusted(block, 'AT1');
            break;
          case 'FROM_END':
            var at1 = Blockly.Python.getAdjusted(block, 'AT1', 1, false,
              Blockly.Python.ORDER_SUBTRACTION);
            at1 = text + '.length - ' + at1;
            break;
          case 'FIRST':
            var at1 = '0';
            break;
          default:
            throw Error('Unhandled option (text_getSubstring).');
        }
        switch (where2) {
          case 'FROM_START':
            var at2 = Blockly.Python.getAdjusted(block, 'AT2', 1);
            break;
          case 'FROM_END':
            var at2 = Blockly.Python.getAdjusted(block, 'AT2', 0, false,
              Blockly.Python.ORDER_SUBTRACTION);
            at2 = text + '.length - ' + at2;
            break;
          case 'LAST':
            var at2 = text + '.length';
            break;
          default:
            throw Error('Unhandled option (text_getSubstring).');
        }
        code = text + '.slice(' + at1 + ', ' + at2 + ')';
      } else {
        var at1 = Blockly.Python.getAdjusted(block, 'AT1');
        var at2 = Blockly.Python.getAdjusted(block, 'AT2');
        var getIndex_ = Blockly.Python.text.getIndex_;
        var wherePascalCase = {
          'FIRST': 'First', 'LAST': 'Last',
          'FROM_START': 'FromStart', 'FROM_END': 'FromEnd'
        };
        var functionName = Blockly.Python.provideFunction_(
          'subsequence' + wherePascalCase[where1] + wherePascalCase[where2],
          ['function ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ +
            '(sequence' +
            // The value for 'FROM_END' and'FROM_START' depends on `at` so
            // we add it as a parameter.
            ((where1 == 'FROM_END' || where1 == 'FROM_START') ? ', at1' : '') +
            ((where2 == 'FROM_END' || where2 == 'FROM_START') ? ', at2' : '') +
            ') {',
          '  var start = ' + getIndex_('sequence', where1, 'at1') + ';',
          '  var end = ' + getIndex_('sequence', where2, 'at2') + ' + 1;',
            '  return sequence.slice(start, end);',
            '}']);
        var code = functionName + '(' + text +
          // The value for 'FROM_END' and 'FROM_START' depends on `at` so we
          // pass it.
          ((where1 == 'FROM_END' || where1 == 'FROM_START') ? ', ' + at1 : '') +
          ((where2 == 'FROM_END' || where2 == 'FROM_START') ? ', ' + at2 : '') +
          ')';
      }
      return [code, Blockly.Python.ORDER_FUNCTION_CALL];
    };
  
    Blockly.Python['text_changeCase'] = function (block) {
      // Change capitalization.
      var OPERATORS = {
        'UPPERCASE': '.toUpperCase()',
        'LOWERCASE': '.toLowerCase()',
        'TITLECASE': null
      };
      var operator = OPERATORS[block.getFieldValue('CASE')];
      var textOrder = operator ? Blockly.Python.ORDER_MEMBER :
        Blockly.Python.ORDER_NONE;
      var text = Blockly.Python.valueToCode(block, 'TEXT',
        textOrder) || '\'\'';
      if (operator) {
        // Upper and lower case are functions built into JavaScript.
        var code = text + operator;
      } else {
        // Title case is not a native JavaScript function.  Define one.
        var functionName = Blockly.Python.provideFunction_(
          'textToTitleCase',
          ['function ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ +
            '(str) {',
            '  return str.replace(/\\S+/g,',
          '      function(txt) {return txt[0].toUpperCase() + ' +
          'txt.substring(1).toLowerCase();});',
            '}']);
        var code = functionName + '(' + text + ')';
      }
      return [code, Blockly.Python.ORDER_FUNCTION_CALL];
    };
  
    Blockly.Python['text_trim'] = function (block) {
      // Trim spaces.
      var OPERATORS = {
        'LEFT': ".replace(/^[\\s\\xa0]+/, '')",
        'RIGHT': ".replace(/[\\s\\xa0]+$/, '')",
        'BOTH': '.trim()'
      };
      var operator = OPERATORS[block.getFieldValue('MODE')];
      var text = Blockly.Python.valueToCode(block, 'TEXT',
        Blockly.Python.ORDER_MEMBER) || '\'\'';
      return [text + operator, Blockly.Python.ORDER_FUNCTION_CALL];
    };
  
    Blockly.Python['text_print'] = function (block) {
      // Print statement.
      var msg = Blockly.Python.valueToCode(block, 'TEXT',
        Blockly.Python.ORDER_NONE) || '\'\'';
      return 'window.alert(' + msg + ');\n';
    };
  
    Blockly.Python['text_prompt_ext'] = function (block) {
      // Prompt function.
      if (block.getField('TEXT')) {
        // Internal message.
        var msg = Blockly.Python.quote_(block.getFieldValue('TEXT'));
      } else {
        // External message.
        var msg = Blockly.Python.valueToCode(block, 'TEXT',
          Blockly.Python.ORDER_NONE) || '\'\'';
      }
      var code = 'window.prompt(' + msg + ')';
      var toNumber = block.getFieldValue('TYPE') == 'NUMBER';
      if (toNumber) {
        code = 'parseFloat(' + code + ')';
      }
      return [code, Blockly.Python.ORDER_FUNCTION_CALL];
    };
  
    Blockly.Python['text_prompt'] = Blockly.Python['text_prompt_ext'];
  
    Blockly.Python['text_count'] = function (block) {
      var text = Blockly.Python.valueToCode(block, 'TEXT',
        Blockly.Python.ORDER_MEMBER) || '\'\'';
      var sub = Blockly.Python.valueToCode(block, 'SUB',
        Blockly.Python.ORDER_NONE) || '\'\'';
      var functionName = Blockly.Python.provideFunction_(
        'textCount',
        ['function ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ +
          '(haystack, needle) {',
          '  if (needle.length === 0) {',
          '    return haystack.length + 1;',
          '  } else {',
          '    return haystack.split(needle).length - 1;',
          '  }',
          '}']);
      var code = functionName + '(' + text + ', ' + sub + ')';
      return [code, Blockly.Python.ORDER_SUBTRACTION];
    };
  
    Blockly.Python['text_replace'] = function (block) {
      var text = Blockly.Python.valueToCode(block, 'TEXT',
        Blockly.Python.ORDER_MEMBER) || '\'\'';
      var from = Blockly.Python.valueToCode(block, 'FROM',
        Blockly.Python.ORDER_NONE) || '\'\'';
      var to = Blockly.Python.valueToCode(block, 'TO',
        Blockly.Python.ORDER_NONE) || '\'\'';
      // The regex escaping code below is taken from the implementation of
      // goog.string.regExpEscape.
      var functionName = Blockly.Python.provideFunction_(
        'textReplace',
        ['function ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ +
          '(haystack, needle, replacement) {',
        '  needle = ' +
        'needle.replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g,"\\\\$1")',
          '                 .replace(/\\x08/g,"\\\\x08");',
          '  return haystack.replace(new RegExp(needle, \'g\'), replacement);',
          '}']);
      var code = functionName + '(' + text + ', ' + from + ', ' + to + ')';
      return [code, Blockly.Python.ORDER_MEMBER];
    };
  
    Blockly.Python['text_reverse'] = function (block) {
      var text = Blockly.Python.valueToCode(block, 'TEXT',
        Blockly.Python.ORDER_MEMBER) || '\'\'';
      var code = text + '.split(\'\').reverse().join(\'\')';
      return [code, Blockly.Python.ORDER_MEMBER];
    };
  
    Blockly.Python['operator_equals'] = function (block) {
      var order = Blockly.Python.ORDER_EQUALITY;
      var argument0 = Blockly.Python.valueToCode(block, 'OPERAND1', order) || '0';
      var argument1 = Blockly.Python.valueToCode(block, 'OPERAND2', order) || '0';
      var code = "str("+ argument0.replace(/'/g, "") +')'+ '==' + 'str(' + argument1.replace(/'/g, "") + ')';
      return [code, order];
    };
  
    Blockly.Python['operator_lt'] = function (block) {
      var order = Blockly.Python.ORDER_EQUALITY;
      var argument0 = Blockly.Python.valueToCode(block, 'OPERAND1', order) || '0';
      var argument1 = Blockly.Python.valueToCode(block, 'OPERAND2', order) || '0';
      var code = argument0.replace(/'/g, "") + ' ' + '<' + ' ' + argument1.replace(/'/g, "");
      return [code, order];
    };
  
    Blockly.Python['operator_gt'] = function (block) {
      var order = Blockly.Python.ORDER_EQUALITY;
      var argument0 = Blockly.Python.valueToCode(block, 'OPERAND1', order) || '0';
      var argument1 = Blockly.Python.valueToCode(block, 'OPERAND2', order) || '0';
      var code = argument0.replace(/'/g, "") + ' ' + '>' + ' ' + argument1.replace(/'/g, "");
      return [code, order];
    };
  
    Blockly.Python['creater_variable'] = function (block) {
      var order = Blockly.Python.ORDER_EQUALITY;
      var type = this.getFieldValue('BACKDROP');
      var variable = Blockly.Python.valueToCode(block, 'OPERAND1', order) || '0';
      variable = variable.replace(/'/g, '');
      var code = type + '  ' + variable + ';\n';
      return code;
    };
  
    Blockly.Python['set_variable'] = function (block) {
      var order = Blockly.Python.ORDER_EQUALITY;
      var argument0 = Blockly.Python.valueToCode(block, 'STEPS', order) || '0';
      var argument1 = Blockly.Python.valueToCode(block, 'STEPS1', order) || '0';
      var code = argument0.replace(/'/g, "") + ' ' + '=' + ' ' + argument1.replace(/'/g, "") + '\n';
      return code;
    };
  
    Blockly.Python['get_variable'] = function (block) {
      var order = Blockly.Python.ORDER_EQUALITY;
      var argument0 = Blockly.Python.valueToCode(block, 'STEPS1', order) || '0';
      var code = argument0.replace(/'/g, "");
      return [code];
    };
  
    Blockly.Python.operator_add = function (block) {
      // +
      const order = Blockly.Python.ORDER_ASSIGNMENT;
      const argument1 = Blockly.Python.valueToCode(block, 'NUM1', order) || 0;
      const argument2 = Blockly.Python.valueToCode(block, 'NUM2', order) || 0;
      const code = `${argument1} + ${argument2}`;
      return [code.replace(/\'/g, ''), order];
    };
  
    Blockly.Python.operator_subtract = function (block) {
      // -
      const order = Blockly.Python.ORDER_ASSIGNMENT;
      const argument1 = Blockly.Python.valueToCode(block, 'NUM1', order) || 0;
      const argument2 = Blockly.Python.valueToCode(block, 'NUM2', order) || 0;
      const code = `${argument1} - ${argument2}`;
      return [code.replace(/\'/g, ''), order];
    };
  
    Blockly.Python.operator_multiply = function (block) {
      // *
      const order = Blockly.Python.ORDER_ASSIGNMENT;
      const argument1 = Blockly.Python.valueToCode(block, 'NUM1', order) || 0;
      const argument2 = Blockly.Python.valueToCode(block, 'NUM2', order) || 0;
      const code = `${argument1} * ${argument2}`;
      return [code.replace(/\'/g, ''), order];
    };
  
    Blockly.Python.operator_divide = function (block) {
      // /
      const order = Blockly.Python.ORDER_ASSIGNMENT;
      const argument1 = Blockly.Python.valueToCode(block, 'NUM1', order) || 0;
      const argument2 = Blockly.Python.valueToCode(block, 'NUM2', order) || 0;
      const code = `${argument1} / ${argument2}`;
      return [code.replace(/\'/g, ''), order];
    };
  
    Blockly.Python.operator_notbools = function (block) {
      const order = Blockly.Python.ORDER_ASSIGNMENT;
      const variable = Blockly.Python.valueToCode(block, 'OPERAND1', order) || '0';
      const code = "not ' '";
      return [code];
    };
  
    Blockly.Python.notis = function () {
      let value_notiss1 = Blockly.Python.valueToCode(this, 'notiss1', Blockly.Python.ORDER_ATOMIC);
      let value_notiss2 = Blockly.Python.valueToCode(this, 'notiss2', Blockly.Python.ORDER_ATOMIC);
      let code = `${value_notiss1.replace(/'/g, '')}!=${value_notiss2.replace(/'/g, '')}`;
      return [code, Blockly.Python.ORDER_ATOMIC];
    };
  
    Blockly.Python.operator_ands = function (block) {
      const order = Blockly.Python.ORDER_ASSIGNMENT;
      const argument1 = Blockly.Python.valueToCode(block, 'OPERAND1', order) || 0;
      const argument2 = Blockly.Python.valueToCode(block, 'OPERAND2', order) || 0;
      const code = `${argument1} and ${argument2}`;
      return [code, order];
    };
  
    Blockly.Python.operator_ors = function (block) {
      // Numeric value.
      const order = Blockly.Python.ORDER_ASSIGNMENT;
      const argument1 = Blockly.Python.valueToCode(block, 'OPERAND1', order) || 0;
      const argument2 = Blockly.Python.valueToCode(block, 'OPERAND2', order) || 0;
      const code = `${argument1} or ${argument2}`;
      return [code, order];
    };
  
    Blockly.Python.operator_bools = function (block) {
      const argument1 = this.getFieldValue('BACKDROP');
      if (argument1 === 'true') return ['True'];
      return ['False'];
    };
  
    Blockly.Python.operator_not = function (block) {
      // Numeric value.
      const order = Blockly.Python.ORDER_ASSIGNMENT;
      const argument1 = Blockly.Python.valueToCode(block, 'OPERAND1', order) || 0;
      const argument2 = Blockly.Python.valueToCode(block, 'OPERAND2', order) || 0;
      const code = `${argument1} not ${argument2}`;
      return [code, order];
    };
  
    Blockly.Python.operator_notbools = function (block) {
      const order = Blockly.Python.ORDER_ASSIGNMENT;
      const variable = Blockly.Python.valueToCode(block, 'OPERAND1', order) || '0';
      const code = `!${variable}`;
      return [code];
    };
  
    Blockly.Python['math_number'] = function (block) {
      // Numeric value.
      var code = parseFloat(block.getFieldValue('NUM'));
      var order = code >= 0 ? Blockly.Python.ORDER_ATOMIC :
        Blockly.Python.ORDER_UNARY_NEGATION;
      return [code, order];
    };
  
    Blockly.Python['math_whole_number'] = function (block) {
      // Numeric value.
      var code = parseFloat(block.getFieldValue('NUM'));
      var order = code >= 0 ? Blockly.Python.ORDER_ATOMIC :
        Blockly.Python.ORDER_UNARY_NEGATION;
      return [code, order];
    };
  
    Blockly.Python.math_number = function (block) {
      // Numeric value.
      const code = parseFloat(block.getFieldValue('NUM'));
      const order = code >= 0 ? Blockly.Python.ORDER_ATOMIC :
        Blockly.Python.ORDER_UNARY_NEGATION;
      return [code, order];
    };
  
    Blockly.Python.math_whole_number = function (block) {
      // Numeric value.
      const code = parseFloat(block.getFieldValue('NUM'));
      const order = code >= 0 ? Blockly.Python.ORDER_ATOMIC :
        Blockly.Python.ORDER_UNARY_NEGATION;
      return [code, order];
    };




    //按键传感器
  Blockly.Python.microbit_button = function(block) {
    var dropdown_microbitButton = this.getFieldValue('microbitButton');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *\n';
    Blockly.Python.definitions_['import_Button'] = 'from input import button\n';
    // Blockly.Python.definitions_['import_button'] = '\n';
    var code =   'button.is_pressed('+ dropdown_microbitButton +')';
    return [code];
  }

  //触摸传感器
  Blockly.Python.microbit_touch= function(block) {
    var dropdown_microbitTouch = this.getFieldValue('microbitTouch');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *\n';
    Blockly.Python.definitions_['import_Touch'] = 'from input import touch\n';
    // Blockly.Python.definitions_['import_touch'] = 'import Touch\n';
    var code = 'touch.is_touched('+ dropdown_microbitTouch +')';
    return [code];
  }

    //碰撞传感器
  Blockly.Python.microbit_knockswitch= function(block) {
    var dropdown_knockswitch = this.getFieldValue('knockswitch');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *\n';
    Blockly.Python.definitions_['import_Collision'] = 'from input import collision\n';
    var code = 'collision.is_collided('+ dropdown_knockswitch +')';
    return [code];
  }

  //旋转电位器
  Blockly.Python.microbit_resistance = function(block) {
    var dropdown_resistance = this.getFieldValue('resistance');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *\n';
    Blockly.Python.definitions_['import_Rotarypotentiometer'] = 'from input import potentiometer\n';
    var code = 'potentiometer.rotary_value('+ dropdown_resistance +')';
    return [code];
  }



  //旋转编码器初始化
  Blockly.Python.microbit_encoderInit = function(block) {
    var dropdown_aPort = this.getFieldValue('aPort');
    var dropdown_bPort = this.getFieldValue('bPort');
    
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *\n';
    Blockly.Python.definitions_['import_encoder'] = 'from sensor import encoder\n';
    Blockly.Python.definitions_['import_encoderAPort'] = 'aPort = '+ dropdown_aPort ;
    Blockly.Python.definitions_['import_encoderBPort'] = 'bPort = '+ dropdown_bPort ;
    Blockly.Python.definitions_['import_encoderDPort'] = 'dPort = '+ dropdown_dPort ;
    return '';
  }

   //旋转编码器
   Blockly.Python.microbit_encoderButtonPressed = function(block) {
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *\n';
    Blockly.Python.definitions_['import_encoder'] = 'from input import encoder\n';
    var dropdown_dPort = this.getFieldValue('dPort');
    Blockly.Python.definitions_['import_encoderDPort' + dropdown_dPort] = 'dPort'+dropdown_dPort+' = '+ dropdown_dPort ;
    var code = 'encoder.is_pressed(dPort'+dropdown_dPort+')';
    return [code];
  }

  //旋转编码器
  Blockly.Python.microbit_encoderPulse = function(block) {
    var dropdown_aPort = this.getFieldValue('aPort');
    var dropdown_bPort = this.getFieldValue('bPort');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *\n';
    Blockly.Python.definitions_['import_encoder'] = 'from input import encoder\n';
    Blockly.Python.definitions_['import_encoderAPort' + dropdown_aPort] = 'aPort'+dropdown_aPort+' = '+ dropdown_aPort ;
    Blockly.Python.definitions_['import_encoderBPort' + dropdown_bPort] = 'bPort'+dropdown_bPort+' = '+ dropdown_bPort ;
    var code = 'encoder.pulse(aPort'+dropdown_aPort+', bPort'+ dropdown_bPort +')';
    return [code];
  }
   
  //钢琴模块初始化
  Blockly.Python.microbit_pianoInit = function(block) {
    var dropdown_pianoCLK = this.getFieldValue('pianoCLK');
    var dropdown_pianoDIO = this.getFieldValue('pianoDIO');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_TouchPiano'] = 'from input import touch_piano';
    Blockly.Python.definitions_['piano_init'] = 'touch_piano.init('+dropdown_pianoCLK+', '+dropdown_pianoDIO+')\n';
    return '';
  }

  //钢琴模块 获取钢琴值
  Blockly.Python.microbit_getPianoKey = function(block) {
    var code = 'key = touch_piano.get_key()\n' ;
    return code;
  }

  //钢琴模块
  Blockly.Python.microbit_piano = function(block) {
    var dropdown_piano2 = this.getFieldValue('piano2');
     Blockly.Python.definitions_['codeLine_pianoData'] = '  key = touch_piano.get_key()';
    var code = 'key == ' + dropdown_piano2;
    return [code];
  }


  //矩阵键盘初始化
  Blockly.Python.microbit_maxtixKeyPadInit = function(block) {
    var dropdown_pianoCLK = this.getFieldValue('maxtixKeypadCLK');
    var dropdown_pianoDIO = this.getFieldValue('maxtixKeypadDIO');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_TouchMaxtixKeypad'] = 'from input import maxtix_keypad';
    Blockly.Python.definitions_['maxtixKeypad_init'] = 'maxtix_keypad.init('+dropdown_pianoCLK+', '+dropdown_pianoDIO+')\n';
    return '';
  }
//矩阵键盘模块 获取键盘按下的值
Blockly.Python.microbit_maxtixKeyPadGetValue = function(block) {
  // var dropdown_piano2 = this.getFieldValue('maxtixKeypad');
  var code = 'key = maxtix_keypad.get_key()\n';
  // var code = 'key == ' + dropdown_piano2;
  return code;
}

//矩阵键盘模块  判断
Blockly.Python.microbit_maxtixKeyPad = function(block) {
  var dropdown_maxtixValue = this.getFieldValue('maxtixKeypad');
  Blockly.Python.definitions_['codeLine_maxtixData'] = '  key = maxtix_keypad.get_key()';
  var code = 'key == ' + dropdown_maxtixValue;
  return [code];
}

  //滑动电位器
  Blockly.Python.microbit_slipresistance = function(block) {
    var dropdown_slipresistance = this.getFieldValue('slipresistance');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *\nimport math';
    Blockly.Python.definitions_['import_slidepotentiometer'] = 'from input import potentiometer\n';
    Blockly.Python.definitions_['codeLine_slidepotentiometer'] = '  slideValue = potentiometer.slide_value('+ dropdown_slipresistance +')\n  slideValue1 = slideValue/1023*100';
    var code = 'int(slideValue1)';
    return [code];
  }

  //摇杆模块初始化
  Blockly.Python.microbit_rockInit = function(block) {
    var dropdown_rockX = this.getFieldValue('rockX');
    var dropdown_rockY = this.getFieldValue('rockY');
    var dropdown_rockB = this.getFieldValue('rockB');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_Rocker'] = 'from input import joystick';
    Blockly.Python.definitions_['rockX'] = 'rockX = '+dropdown_rockX+'';
    Blockly.Python.definitions_['rockY'] = 'rockY = '+dropdown_rockY+'';
    Blockly.Python.definitions_['rockB'] = 'rockB = '+dropdown_rockB+'';
    return '';
  }

    // // 获取摇杆数据数组
    Blockly.Python.microbit_rockData = function(block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_Rocker'] = 'from input import joystick';
      var dropdown_rockB = this.getFieldValue('rockB');
      Blockly.Python.definitions_['import_rockB' + dropdown_rockB] = 'rockB'+dropdown_rockB+' = '+dropdown_rockB+'';
      var code = "joystick.is_pressed(rockB"+dropdown_rockB+")";
      return [code];
    }
 //  获取摇杆值
  Blockly.Python.microbit_rock = function(block) {
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_Rocker'] = 'from input import joystick';
    var dropdown_rockX = this.getFieldValue('rockX');
    var dropdown_rockY = this.getFieldValue('rockY');
    Blockly.Python.definitions_['import_rockX' + dropdown_rockX] = 'rockX' + dropdown_rockX + ' = ' + dropdown_rockX + '';
    Blockly.Python.definitions_['import_rockY' + dropdown_rockY] = 'rockY' + dropdown_rockY + ' = ' + dropdown_rockY + '';
    var dropdown_rock = this.getFieldValue('rock2');
    var code = '';
    if("x" == dropdown_rock){
      code = 'joystick.read_x_analog(rockX'+ dropdown_rockX +')';
    }else{
      code = 'joystick.read_y_analog(rockY'+ dropdown_rockY +')';
    }
    return [code];
  }

   //led
   Blockly.Python.microbit_led = function(block) {
      var dropdown_ledPort = this.getFieldValue('ledPort');
      var dropdown_ledStatus = this.getFieldValue('ledStatus');
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_LED'] = 'from monitor import led';
      var code = "led.light("+dropdown_ledPort+', '+dropdown_ledStatus+')\n';
      return code;
   }

   //TM1650 数码管初始化
  Blockly.Python.microbit_tm1650Init = function(block) {
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_TM1650'] = 'from monitor import tm1650';
    // var code = 'TouchPiano.read('+ dropdown_pianoCLK +','+ dropdown_pianoDIO +') == ' + dropdown_piano2;
    var dropdown_tm1650Intensity = this.getFieldValue('tm1650Intensity');
    return 'tm1650.on('+dropdown_tm1650Intensity+')\n';
  }
  
   //TM1650 数码管展示
   Blockly.Python.microbit_tm1650display = function(block) {
    var dropdown_TM1650Bit = this.getFieldValue('TM1650Bit');
    //  var value_serialprint16nums = Blockly.Python.valueToCode(this, 'serialprint16nums', Blockly.Python.ORDER_ATOMIC);
      var dropdown_tm1650Data = Blockly.Python.valueToCode(this, 'tm1650Data', Blockly.Python.ORDER_ATOMIC);
      // var code = 'TouchPiano.read('+ dropdown_pianoCLK +','+ dropdown_pianoDIO +') == ' + dropdown_piano2;
      return 'tm1650.show_digit('+dropdown_tm1650Data+', '+dropdown_TM1650Bit+')\n';
  }

  // tm1650数码管显示数字
  Blockly.Python.microbit_tm1650ShowNumber = function(block){
    var dropdown_tm1650Number = Blockly.Python.valueToCode(this, 'tm1650Number', Blockly.Python.ORDER_ATOMIC);
    return 'tm1650.show_number('+dropdown_tm1650Number +')\n';
  };

  // tm1650数码管显示小数点
  Blockly.Python.microbit_tm1650PointDisplay = function(block){
    var dropdown_tm1650Point = this.getFieldValue('tm1650Point');
    var dropdown_TM1650PointBit = this.getFieldValue('TM1650PointBit');
    return 'tm1650.show_dp('+dropdown_TM1650PointBit+', '+dropdown_tm1650Point+')\n';
  };


  //TM1650 数码管清屏
  Blockly.Python.microbit_tm1650Clear = function(block) {
    // var dropdown_TM1650Bit = this.getFieldValue('TM1650Bit1');
    
    return 'tm1650.clear()\n';
  }


  
   //LCD1602 初始化
   Blockly.Python.microbit_lcdinit = function(block) {
    var dropdown_lcd1602Address = Blockly.Python.valueToCode(this, 'microbit_lcdinits', Blockly.Python.ORDER_ATOMIC);
    // var dropdown_lcd1602Address =  Blockly.Python.valueToCode(this, 'microbit_lcdinits', Blockly.Python.ORDER_ATOMIC); 
    
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_lcd1602'] = 'from monitor import lcd1602';
    return 'lcd1602.init('+ dropdown_lcd1602Address +')\n';
  }

   //LCD1602 清屏
   Blockly.Python.microbit_lcdClear = function(block) {
    return 'lcd1602.clear()\n';
  }

    //LCD1602 打开关闭显示屏
    Blockly.Python.microbit_lcdScreen = function(block) {
      var dropdown_lcdScreen = this.getFieldValue('lcdScreen');
      return 'lcd1602.'+ dropdown_lcdScreen +'\n';
    }
  
     //LCD1602 打开关闭背光
     Blockly.Python.microbit_lcdBackLight = function(block) {
      var dropdown_lcdBackLight = this.getFieldValue('lcdBackLight');
      return 'lcd1602.backlight_'+ dropdown_lcdBackLight +'\n';
    }
  
    //LCD1602 光标移动
    Blockly.Python.microbit_lcdShift = function(block) {
      var dropdown_lcdShift = this.getFieldValue('lcdShift');
      return 'lcd1602.shift_'+ dropdown_lcdShift +'\n';
    }

    //LCD1602 显示
    Blockly.Python.microbit_lcdposition = function(block) {
      var dropdown_lcd1602Row =  Blockly.Python.valueToCode(this, 'row', Blockly.Python.ORDER_ATOMIC); 
      var dropdown_lcd1602Col =  Blockly.Python.valueToCode(this, 'col', Blockly.Python.ORDER_ATOMIC); 
                                    // Blockly.Python.valueToCode(this, 'initAddress', Blockly.Python.ORDER_ATOMIC);
      var dropdown_lcd1602lcdStr =  Blockly.Python.valueToCode(this, 'lcdStr', Blockly.Python.ORDER_ATOMIC); 
      dropdown_lcd1602lcdStr = dropdown_lcd1602lcdStr.replace(/'/g,"");
      return 'lcd1602.show_string('+dropdown_lcd1602lcdStr+', ' + dropdown_lcd1602Col + ', ' + dropdown_lcd1602Row + ' - 1)\n';
    }
  


   //TM1637 数码管初始化
   Blockly.Python.microbit_tm1637Init = function(block) {
    var dropdown_tm1637CLK = this.getFieldValue('tm1637CLK');
    var dropdown_tm1637DIO = this.getFieldValue('tm1637DIO');
    var dropdown_tm1637Intensity = this.getFieldValue('tm1637Intensity');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_TM1637'] = 'from monitor import tm1637';
    return 'tm1637.init('+ dropdown_tm1637CLK + ', '+ dropdown_tm1637DIO + ', '+dropdown_tm1637Intensity +')\n';
  }
  
   //TM1637 数码管
   Blockly.Python.microbit_tm1637display = function(block) {
      var dropdown_TM1637Bit = this.getFieldValue('TM1637Bit');
      var dropdown_tm1637Data = Blockly.Python.valueToCode(this, 'tm1637Data', Blockly.Python.ORDER_ATOMIC);
      var dropdown_TM1637Point = this.getFieldValue('tm1637Point');
      return 'tm1637.show_digit(' + dropdown_tm1637Data + ', '+ dropdown_TM1637Bit + ', ' + dropdown_TM1637Point + ')\n';
  }

  // tm1650数码管显示数字
  Blockly.Python.microbit_tm1637ShowNumber = function(block){
    var dropdown_tm1637Number = Blockly.Python.valueToCode(this, 'tm1637Number', Blockly.Python.ORDER_ATOMIC);
    var dropdown_TM1637Point = this.getFieldValue('tm1637Point');
    return 'tm1637.show_number(' + dropdown_tm1637Number + ', ' + dropdown_TM1637Point +')\n';
  };

  //TM1637 数码管清屏
  Blockly.Python.microbit_tm1637Clear = function(block) {
    var dropdown_TM1650Bit = this.getFieldValue('TM1637Bit1');
    return 'tm1637.clear('+dropdown_TM1650Bit+')\n';
  }

    //7219初始化
    Blockly.Python.microbit_matrix7219Init = function(block) {
      var dropdown_matrix_din = this.getFieldValue('matrix_din');
      var dropdown_matrix_cs = this.getFieldValue('matrix_cs');
      var dropdown_matrix_sda = this.getFieldValue('matrix_sda');
      var dropdown_matrix_intensity = this.getFieldValue('initIntensity');
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_matrix7219'] = 'from monitor import matrix7219';
      return 'matrix7219.init('+dropdown_matrix_din+ ', '+ dropdown_matrix_cs + ', '+ dropdown_matrix_sda+', '+dropdown_matrix_intensity +')\n';
    }
    
    //7219 点阵屏点显示亮度
    Blockly.Python.microbit_matrix7219SetPixel = function(block) {
      // var dropdown_matrixX = Blockly.Python.valueToCode(this, 'matrixX', Blockly.Python.ORDER_ATOMIC);
      // var dropdown_matrixY = Blockly.Python.valueToCode(this, 'matrixY', Blockly.Python.ORDER_ATOMIC);
      // var dropdown_intensity = Blockly.Python.valueToCode(this, 'intensity', Blockly.Python.ORDER_ATOMIC);
      var dropdown_matrixX = this.getFieldValue('matrixX');
      var dropdown_matrixY = this.getFieldValue('matrixY');
      var dropdown_intensity = this.getFieldValue('intensity');
      return 'matrix7219.set_pixel('+dropdown_matrixX+ ', '+ dropdown_matrixY + ', '+ dropdown_intensity +')\n';
    }

      //7219 点阵图像
    Blockly.Python.microbit_matrix7219Draw = function(block) {
        var choice = block.getFieldValue('lattice');
        if (choice.length <= 0) {
          choice = "0000000000000000000000000000000000000000000000000000000000000000";
        }else{
          choice = choice.substring(2,choice.length);
        }
        let result = Blockly.Python.hex_to_bin(choice);
      var choiceArrray = [];
      for (var i = 0; i < result.length / 8; i++) {
        choiceArrray.push(result.substring(i * 8, i * 8 + 8).replace(/1/g, '1'))
      }
      var image = '"' + choiceArrray[0]+ ':'+ choiceArrray[1]+ ':'+ choiceArrray[2]+ ':'+ choiceArrray[3]+ ':'+ choiceArrray[4]+ ':'+choiceArrray[5]+ ':'+choiceArrray[6]+ ':'+choiceArrray[7]+ '"';
      return 'matrix7219.draw('+ image +')\n';
    }


      Blockly.Python.hex_to_bin= function (str) {
        let hex_array = [{key:0,val:"0000"},{key:1,val:"0001"},{key:2,val:"0010"},{key:3,val:"0011"},{key:4,val:"0100"},{key:5,val:"0101"},{key:6,val:"0110"},{key:7,val:"0111"},
        {key:8,val:"1000"},{key:9,val:"1001"},{key:'a',val:"1010"},{key:'b',val:"1011"},{key:'c',val:"1100"},{key:'d',val:"1101"},{key:'e',val:"1110"},{key:'f',val:"1111"}]
        let value=""
        for(let i=0;i<str.length;i++){
            for(let j=0;j<hex_array.length;j++){
                if(str.charAt(i).toLowerCase()== hex_array[j].key){
                    value = value.concat(hex_array[j].val)
                    break
                }
            }
        }
        return value
      };




//交通灯模块初始化
Blockly.Python.microbit_trafficlightsInit = function(block) {
  var dropdown_green = this.getFieldValue('green');
  var dropdown_yellow = this.getFieldValue('yellow');
  var dropdown_red = this.getFieldValue('red');
  Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
  Blockly.Python.definitions_['import_Waterlight'] = 'from monitor import traffic';
  Blockly.Python.definitions_['green'] = 'trafficGreenPort = ' + dropdown_green + '';
  Blockly.Python.definitions_['yellow'] = 'trafficYellowPort = ' + dropdown_yellow + '';
  Blockly.Python.definitions_['red'] = 'trafficRedPort = '+dropdown_red+'';
  return '';
}

    //交通灯模块
  Blockly.Python.microbit_trafficlights = function(block) {
    var dropdown_red = this.getFieldValue('trafficlightsRed');
    var dropdown_green = this.getFieldValue('trafficlightsGreen');
    var dropdown_yellow = this.getFieldValue('trafficlightsYellow');
    var dropdown_lightTime1 = Blockly.Python.valueToCode(this, 'lightTime1', Blockly.Python.ORDER_ATOMIC);
    var code = "traffic.light(trafficGreenPort, "+ dropdown_green+")\ntraffic.light(trafficYellowPort, "+ dropdown_yellow+")\ntraffic.light(trafficRedPort, "+dropdown_red + ")\nsleep(" +dropdown_lightTime1 + ")\n";
    return code;
  }


  
//RGB模块初始化
Blockly.Python.microbit_rgbcolorInit = function(block) {
  var dropdown_green = this.getFieldValue('green');
  var dropdown_blue = this.getFieldValue('blue');
  var dropdown_red = this.getFieldValue('red');
  Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
  Blockly.Python.definitions_['import_RGB'] = 'from monitor import led';
  Blockly.Python.definitions_['green'] = 'greenPort = '+dropdown_green+'';
  Blockly.Python.definitions_['blue'] = 'bluePort = '+dropdown_blue+'';
  Blockly.Python.definitions_['red'] = 'redPort = '+dropdown_red+'';
  return '';
}

 //RGB灯模块
 Blockly.Python.microbit_rgbcolor = function(block) {
  // var dropdown_red = Blockly.Python.valueToCode(this, 'rgbr', Blockly.Python.ORDER_ATOMIC);
  // var dropdown_green = Blockly.Python.valueToCode(this, 'rgbg', Blockly.Python.ORDER_ATOMIC);
  // var dropdown_blue = Blockly.Python.valueToCode(this, 'rgbb', Blockly.Python.ORDER_ATOMIC);
  var dropdown_colour = block.childBlocks_[0].colour_;
  var colorStr = dropdown_colour.colorRgb();
  var red_color = 0;
  var blue_color = 0;
  var green_color = 0;
  if (colorStr) {
    var colorArr = colorStr.split(",");
    red_color = colorArr[0];
    green_color = colorArr[1];
    blue_color = colorArr[2];
 }
  var code = "led.brightness(greenPort, " + green_color + ")\nled.brightness(bluePort, " + blue_color + ")\nled.brightness(redPort, " + red_color + ")\n";
  return code;
}


 //直流电机模块
 Blockly.Python.microbit_motor = function(block) {
  var dropdown_motorINA = this.getFieldValue('INA');
  var dropdown_motorINB = this.getFieldValue('INB');
  var dropdown_direction = this.getFieldValue('direction');
  var dropdown_motorSpeed = Blockly.Python.valueToCode(this, 'motorSpeed', Blockly.Python.ORDER_ATOMIC);
  Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
  Blockly.Python.definitions_['import_Motor'] = 'from actuator import dc_motor';
  var code = "";
  if(dropdown_direction === "forward"){
    code = "dc_motor.run("+ dropdown_motorINA +", "+ dropdown_motorINB +", int("+ dropdown_motorSpeed +"))\n";
  }else if(dropdown_direction === "reverse"){
    code = "dc_motor.run("+ dropdown_motorINA +", "+ dropdown_motorINB +", int(-"+ dropdown_motorSpeed +"))\n";
  }
  return code;
}

  //无源蜂鸣器模块
  Blockly.Python.microbit_passive_buzzer = function(block) {
    var dropdown_song = this.getFieldValue('song');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_music'] = 'import music';
    var code = "music.play("+ dropdown_song +")\n";
    return code;
  }

   //有源蜂鸣器模块
   Blockly.Python.microbit_buzzer = function(block) {
    var dropdown_buzzer = this.getFieldValue('buzzer');
    var dropdown_buzzerStatus = this.getFieldValue('buzzerStatus');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_Buzzer'] = 'from actuator import buzzer';
    var code = "buzzer.sing("+ dropdown_buzzer +", "+ dropdown_buzzerStatus +")\n";
    return code;
  }

  //继电器模块
  Blockly.Python.microbit_relay = function(block) {
        var dropdown_relay = this.getFieldValue('relay');
    var dropdown_relayStatus = this.getFieldValue('relayStatus');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_Relay'] = 'from actuator import relay';
    var code = "relay.control("+ dropdown_relay +", "+ dropdown_relayStatus +")\n";
    return code;
  }

  //舵机模块
  Blockly.Python.microbit_servo = function(block) {
    var dropdown_servoPort = this.getFieldValue('servoPort');
    var dropdown_servoAngle = Blockly.Python.valueToCode(this, 'servoAngle', Blockly.Python.ORDER_ATOMIC);
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_Relay'] = 'from actuator import servo';
    var code = "servo.angle("+ dropdown_servoPort + ", " + dropdown_servoAngle +")\n";
    return code;
  }

  //激光发射模块
  Blockly.Python.microbit_laser = function(block) {
    var dropdown_laser = this.getFieldValue('laser');
    var dropdown_laserStatus = this.getFieldValue('laserStatus');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_LightEmission'] = 'from actuator import laser';
    var code = "laser.emission("+ dropdown_laser +", "+ dropdown_laserStatus +")\n";
    return code;
  }


  //红外接收模块
  Blockly.Python.microbit_irInit = function(block) {
    var dropdown_irPort = this.getFieldValue('irPort');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_nec_ir'] = 'from sensor import nec_ir';
    Blockly.Python.definitions_['import_nec_irInit'] = 'nec_ir.init('+ dropdown_irPort +')';
    return '';
  }

  //红外接收模块
  Blockly.Python.microbit_ir = function(block) {
    var dropdown_mappingValue = this.getFieldValue('mappingValue');
    Blockly.Python.definitions_['codeLine_irData'] = '  key = nec_ir.get_code()';
    var code = "key == "+dropdown_mappingValue;
    return [code];
  }

   //红外接收模块
   Blockly.Python.microbit_irLogic = function(block) {
      var code = "nec_ir.get_code()";
    return [code];
  }

 //声音传感器模块
  Blockly.Python.microbit_vioce = function(block) {
    var dropdown_vioceDigital = this.getFieldValue('vioceDigital');
    var dropdown_vioceAnalog = this.getFieldValue('vioceAnalog');
    // var dropdown_vioceValue = this.getFieldValue('vioceValue');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_Sound'] = 'from sensor import sound';
    Blockly.Python.definitions_['import_vioceDigital' ] = 'vioceDigitalPort = '+dropdown_vioceDigital;
    Blockly.Python.definitions_['import_vioceAnalog' ] = 'vioceAnalogPort = '+dropdown_vioceAnalog;
    return '';
  }

  // // 获取声音的数字值
  Blockly.Python.microbit_vioceDigital = function(block) {
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_Sound'] = 'from sensor import sound';
    var dropdown_vioceDigital = this.getFieldValue('vioceDigital');
    Blockly.Python.definitions_['import_vioceDigital' + dropdown_vioceDigital] = 'vioceDigitalPort' + dropdown_vioceDigital + ' = ' + dropdown_vioceDigital;
    var code = "sound.is_detected(vioceDigitalPort" + dropdown_vioceDigital + ")";
    return [code];
  }
//  获取声音的模拟值
Blockly.Python.microbit_vioceAnalog = function(block) {
  Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_Sound'] = 'from sensor import sound';
    var dropdown_vioceAnalog = this.getFieldValue('vioceAnalog');
    Blockly.Python.definitions_['import_vioceAnalog' + dropdown_vioceAnalog] = 'vioceAnalogPort' + dropdown_vioceAnalog + ' = ' + dropdown_vioceAnalog;
  var code = "sound.get_value(vioceAnalogPort" + dropdown_vioceAnalog + ")";
    return [code];
}


//  获取lm35温度
Blockly.Python.microbit_lm35 = function(block) {
  Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_lm35'] = 'from sensor import lm35';
    var dropdown_lm35Pin = this.getFieldValue('lm35Pin');
    Blockly.Python.definitions_['import_lm35Pin' + dropdown_lm35Pin] = 'lm35Port' + dropdown_lm35Pin + ' = ' + dropdown_lm35Pin;
  var code = "lm35.read_temps(lm35Port" + dropdown_lm35Pin + ")";
    return [code];
}

//气体传感器模块
Blockly.Python.microbit_gas = function(block) {
  var dropdown_gasDigital = this.getFieldValue('gasDigital');
  var dropdown_gasAnalog = this.getFieldValue('gasAnalog');
  Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
  Blockly.Python.definitions_['import_gas'] = 'from sensor import gas_detector';
  Blockly.Python.definitions_['import_gasDigital'] = 'gasDigitalPort = '+dropdown_gasDigital;
  Blockly.Python.definitions_['import_gasAnalog'] = 'gasAnalogPort = '+dropdown_gasAnalog;
  return '';
}

// // 获取气体的模拟值
Blockly.Python.microbit_gasAnalog = function(block) {
  Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
  Blockly.Python.definitions_['import_gas'] = 'from sensor import gas_detector';
  var dropdown_gasAnalog = this.getFieldValue('gasAnalog');
  Blockly.Python.definitions_['import_gasAnalog' + dropdown_gasAnalog] = 'gasAnalogPort' + dropdown_gasAnalog + ' = '+dropdown_gasAnalog;
  var code = "gas_detector.get_value(gasAnalogPort" + dropdown_gasAnalog + ")";
  return [code];
}
//  获取气体的数字值
Blockly.Python.microbit_gasDigital = function(block) {
  Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
  Blockly.Python.definitions_['import_gas'] = 'from sensor import gas_detector';
  var dropdown_gasDigital = this.getFieldValue('gasDigital');
  Blockly.Python.definitions_['import_gasDigital' + dropdown_gasDigital] = 'gasDigitalPort' + dropdown_gasDigital + ' = '+dropdown_gasDigital;
  var code = "gas_detector.is_detected(gasDigitalPort" + dropdown_gasDigital + ")";
  return [code];
}

  
 //光敏传感器模块
  Blockly.Python.microbit_light = function(block) {
    var dropdown_microbitLight = this.getFieldValue('microbitLight');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_music'] = 'from sensor import photosensitive';
    var code = "photosensitive.get_value("+ dropdown_microbitLight +")";
    return [code];
  }

  //热敏传感器模块
  Blockly.Python.microbit_thermosensitive = function(block) {
    var dropdown_thermosensitive = this.getFieldValue('thermosensitive');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_Thermal'] = 'from sensor import thermal';
    var code = "thermal.get_value("+ dropdown_thermosensitive +")";
    return [code];
  }

  //火焰传感器模块
  Blockly.Python.microbit_fire = function(block) {
    var dropdown_fireeAnalog = this.getFieldValue('fireAnalog');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_Flame'] = 'from sensor import flame';
    Blockly.Python.definitions_['import_fireeAnalog' + dropdown_fireeAnalog] = 'fireDigital' + dropdown_fireeAnalog + ' = '+ dropdown_fireeAnalog;
    var code = "flame.get_value(fireDigital" + dropdown_fireeAnalog + ")";
    return [code];
  }

  //火焰传感器模块
  Blockly.Python.microbit_fireReadDigital = function(block) {
    var dropdown_fireDigital = this.getFieldValue('fireDigital');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_Flame'] = 'from sensor import flame';
    Blockly.Python.definitions_['import_fireDigital' + dropdown_fireDigital] = 'fireDigital' + dropdown_fireDigital + ' = '+dropdown_fireDigital;
    // Blockly.Python.definitions_['import_rainAnalog'] = 'rainAnalogPort' + dropdown_raineAnalog + ' = '+dropdown_raineAnalog;
    var code = "flame.is_fire(fireDigital" + dropdown_fireDigital + ")";
    return [code];
  }

  //土壤湿度传感器模块
  Blockly.Python.microbit_soil = function(block) {
    var dropdown_soil = this.getFieldValue('soil');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_Soilmoisture'] = 'from sensor import soilmoisture';
    var code = "soilmoisture.get_value("+ dropdown_soil +")";
    return [code];
  }

  //土壤湿度传感器模块
  Blockly.Python.microbit_DHT11 = function(block) {
    var dropdown_dht11Port = this.getFieldValue('dht11Port');
    var dropdown_dnt11Func = this.getFieldValue('dnt11Func');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_dht11'] = 'from sensor import dht11';
    Blockly.Python.definitions_['import_dht11Init'] = 'dht11.init('+dropdown_dht11Port+')';
    var code = "dht11."+ dropdown_dnt11Func ;
    return [code];
  }

  
  //雨滴传感器模块
  Blockly.Python.microbit_rain = function(block) {
    var dropdown_rainDigital = this.getFieldValue('rainDigital');
    var dropdown_raineAnalog = this.getFieldValue('rainAnalog');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_water'] = 'from sensor import water';
    Blockly.Python.definitions_['import_rainDigital'] = 'rainDigitalPort = '+dropdown_rainDigital;
    Blockly.Python.definitions_['import_rainAnalog'] = 'rainAnalogPort = '+dropdown_raineAnalog;
    return ''; 
  }

  //获取雨滴的模拟值
  Blockly.Python.microbit_rainAnalog = function(block) {
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_water'] = 'from sensor import water';
    var dropdown_raineAnalog = this.getFieldValue('rainAnalog');
    Blockly.Python.definitions_['import_rainAnalog' + dropdown_raineAnalog] = 'rainAnalogPort' + dropdown_raineAnalog + ' = '+dropdown_raineAnalog;
    var code = "water.get_value(rainAnalogPort" + dropdown_raineAnalog + ")";
    return [code];
  }

  //  获取雨滴的数字值
  Blockly.Python.microbit_rainDigital = function(block) {
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_water'] = 'from sensor import water';
    var dropdown_rainDigital = this.getFieldValue('rainDigital');
    Blockly.Python.definitions_['import_rainDigital' + dropdown_rainDigital] = 'rainDigitalPort' + dropdown_rainDigital + ' = '+dropdown_rainDigital;
    var code = "water.is_droplets(rainDigitalPort" + dropdown_rainDigital + ")";
    return [code];
  }


    //水深传感器模块
    Blockly.Python.microbit_waterdeep = function(block) {
      var dropdown_waterdeep = this.getFieldValue('waterdeep');
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_water'] = 'from sensor import water';
      var code = "water.get_depth("+ dropdown_waterdeep +")";
      return [code];
    }

     //人体热释电传感器模块
     Blockly.Python.microbit_body = function(block) {
      var dropdown_body = this.getFieldValue('body');
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_PIR'] = 'from sensor import human_body';
      var code = "human_body.is_detected("+ dropdown_body +")";
      return [code];
    }

     //红外循迹传感器模块
     Blockly.Python.microbit_track = function(block) {
      var dropdown_track = this.getFieldValue('track');
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_music'] = 'from sensor import infrared_trace';
      var code = "infrared_trace.is_black("+ dropdown_track +")";
      return [code];
    }

    //磁簧开关传感器模块
    Blockly.Python.microbit_reed_switch = function(block) {
      var dropdown_reedPort = this.getFieldValue('reedPort');
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_Magneticswitch'] = 'from sensor import magnetic';
      var code = "magnetic.is_detected("+ dropdown_reedPort +")";
      return [code];
    }

    //灰度传感器模块
    Blockly.Python.microbit_grayscale = function(block) {
      var dropdown_grayscale = this.getFieldValue('grayscale');
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_Grayscale'] = 'from sensor import grayscale';
      var code = "grayscale.get_value("+ dropdown_grayscale +")";
      return [code];
    }

     //震动传感器模块
  Blockly.Python.microbit_shock = function(block) {
    var dropdown_shockDigital = this.getFieldValue('shockDigital');
    var dropdown_shockeAnalog = this.getFieldValue('shockAnalog');
    var dropdown_shockValue = this.getFieldValue('shockValue');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_Shock'] = 'from sensor import Shock';
    var code = "";
    if(dropdown_shockValue === "1"){
      code = "Shock.read_digital("+dropdown_shockDigital+")";
    }else if(dropdown_shockValue === "2"){
      code = "Shock.read_analog("+ dropdown_shockeAnalog +")";
    }
    return [code];
  }

  //获取震动的模拟值
  Blockly.Python.microbit_shockAnalog = function(block) {
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_shock'] = 'from sensor import shock';
    var dropdown_shockAnalog = this.getFieldValue('shockAnalog');
    Blockly.Python.definitions_['import_shockAnalog' + dropdown_shockAnalog] = 'shockAnalog' + dropdown_shockAnalog + ' = ' + dropdown_shockAnalog;
    var code = "shock.get_value(shockAnalog" + dropdown_shockAnalog + ")";
    return [code];
  }
  
  //  获取震动的数字值
  Blockly.Python.microbit_shockDigital = function(block) {
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_shock'] = 'from sensor import shock';
    var dropdown_shockDigital = this.getFieldValue('shockDigital');
    Blockly.Python.definitions_['import_shockDigital' + dropdown_shockDigital] = 'shockDigital' + dropdown_shockDigital + ' = ' + dropdown_shockDigital;
    var code = "shock.is_shocks(shockDigital" + dropdown_shockDigital + ")";
    return [code];
  }

   //获取避障的模拟值
   Blockly.Python.microbit_AvoidanceAnalog = function(block) {
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    var dropdown_AvoidanceAnalog = this.getFieldValue('avoidanceAnalog');
    //Blockly.Python.definitions_['import_shockAnalog' + dropdown_shockAnalog] = 'shockAnalog' + dropdown_shockAnalog + ' = ' + dropdown_shockAnalog;
    var code = dropdown_AvoidanceAnalog +  ".read_analog()";
    return [code];
  }
  
  //  获取避障的数字值
  Blockly.Python.microbit_AvoidanceDigital = function(block) {
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    var dropdown_AvoidanceDigital = this.getFieldValue('avoidanceDigital');
    //Blockly.Python.definitions_['import_shockDigital' + dropdown_shockDigital] = 'shockDigital' + dropdown_shockDigital + ' = ' + dropdown_shockDigital;
    var code = dropdown_AvoidanceDigital +  ".read_digital()";
    return [code];
  }

   //倾斜传感器模块
   Blockly.Python.microbit_tilt = function(block) {
    var dropdown_tilt = this.getFieldValue('tilt');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_tilt'] = 'from sensor import tilt_switch';
    var code = "tilt_switch.is_tilted("+ dropdown_tilt +")";
    return [code];
  }

  //RGB超声波传感器模块初始化
  Blockly.Python.microbit_rgbUltrasonicInit = function(block) {
    var dropdown_ioPort = this.getFieldValue('ioPort');
    var dropdown_rgbPort = this.getFieldValue('rgbPort');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_ultrasonic'] = 'from sensor import ultrasonic';
    Blockly.Python.definitions_['import_neopixel'] = 'import neopixel';
    Blockly.Python.definitions_['import_rgbPort'] = 'rgbPort = ' + dropdown_rgbPort ;
    Blockly.Python.definitions_['import_ioPort'] = 'ioPort = ' +dropdown_ioPort;
    Blockly.Python.definitions_['import_rgbUltrasonicInit'] = 'ultrasonic.init_rus_04('+dropdown_ioPort+', '+dropdown_rgbPort+')\n';
    return "";
  }

  //RGB超声波传感器模块获取距离
  Blockly.Python.microbit_rgbUltrasonicDistance = function(block) {
    var code = "ultrasonic.get_distance()";
    return [code];
  }

  //RGB超声波传感器模块
  Blockly.Python.microbit_rgbUltrasonicColor = function(block) {
    var dropdown_rgbLight = this.getFieldValue('rgbLight');
    var dropdown_rgbSpecial = this.getFieldValue('rgbSpecial');
    var dropdown_rgbUlr = 0;
    var dropdown_rgbUlg = 0;
    var dropdown_rgbUlb = 0;
    var dropdown_rgbBrightness = Blockly.Python.valueToCode(this, 'rgbBrightness', Blockly.Python.ORDER_ATOMIC);
    
    var color = '';
    var special = "";
    var brightness = "";
    var dropdown_colour = block.childBlocks_[1].colour_;
      var colorStr = dropdown_colour.colorRgb();
      if (colorStr) {
        var colorArr = colorStr.split(",");
        dropdown_rgbUlr = colorArr[0];
        dropdown_rgbUlg = colorArr[1];
        dropdown_rgbUlb = colorArr[2];
     }
    if(dropdown_rgbLight === 'right'){
      color = 'np[0] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\nnp[1] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\nnp[2] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\n'
      // + 'np[3] = (0, 0, 0)\nnp[4] = (0, 0, 0)\nnp[5] = (0, 0, 0)\n'
      ;
      special = "np."+ dropdown_rgbSpecial +"(0, 2)\n";
      brightness = 'np.brightness(0, 2, '+dropdown_rgbBrightness+')\n';
    }else if(dropdown_rgbLight === 'left'){
      color = 
      // 'np[0] = (0, 0, 0)\nnp[1] = (0, 0, 0)\nnp[2] = (0, 0, 0)\n'
      // +
       'np[3] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\nnp[4] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\nnp[5] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\n';
      special = "np."+ dropdown_rgbSpecial +"(3, 5)\n";
      brightness = 'np.brightness(3, 5, '+dropdown_rgbBrightness+')\n';
    }else{
      color = 'np[0] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\nnp[1] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\nnp[2] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\n'
      +'np[3] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\nnp[4] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\nnp[5] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\n'
      ;
      special = "np."+ dropdown_rgbSpecial +"(0, 5)\n";
      brightness = 'np.brightness(0, 5, '+dropdown_rgbBrightness+')\n';
    }
    Blockly.Python.definitions_['import_data'] = 'np = neopixel.NeoPixel(rgbPort, 6)\n'+ color;
    Blockly.Python.definitions_['import_brightness'] = brightness;
    return special;
  }

  //普通超声波传感器模块初始化
  Blockly.Python.microbit_ultrasonicInit = function(block) {
    var dropdown_trigPort = this.getFieldValue('trigPort');
    var dropdown_echoPort = this.getFieldValue('echoPort');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_ultrasonic'] = 'from sensor import ultrasonic';
    Blockly.Python.definitions_['import_ultrasonicInit'] = 'ultrasonic.init_hc_sr04('+dropdown_trigPort+', '+dropdown_echoPort+')\n';
    return "";
  }

  //普通超声波传感器模块获取距离
  Blockly.Python.microbit_ultrasonicDistance = function(block) {
    var code = "ultrasonic.get_hc_sr04_distance()";
    return [code];
  }



  Blockly.Python.math_positive_number = Blockly.Python.math_whole_number;

  return Blockly;
}

module.exports = AddSensorbitCode;
